23.4 Stochastic Gradient Methods

Training a neural network almost never uses the exact gradient of its loss. Instead of sweeping through the entire dataset for every update, each step computes the gradient on a random minibatch of a few hundred examples. Every section so far assumed exact gradients, where curvature determines the number of steps and convexity turns any stationary point into a global minimizer. A minibatch gradient points in the right direction on average, but it is noisy, and that noise changes the central question of optimization from how many steps a run needs to how close to the minimizer it can get. This section asks what gradient noise costs and how we can overcome it.

Even the simplest possible loss reveals the cost. Consider f(x)=12x2f(x) = \tfrac12 x^2, whose minimizer is 00, and suppose we add independent noise of unit variance to every gradient while taking constant steps of size η=0.1\eta = 0.1. With exact gradients, each step would shrink xx by a tenth, driving the iterate as close to 00 as we like. With noisy gradients, the iterate never settles: its mean square converges to 0.1/1.9≈0.0530.1/1.9 \approx 0.053, so it wanders roughly 0.230.23 away from the minimizer no matter how many steps we take. Three quantities determine how low the loss can get: the size of the noise, the step size, and the number of steps we can afford.

We begin by quantifying the noise of a minibatch gradient. On a quadratic objective, we then compute where a fixed step size stalls and how many steps it takes to get there. Next, we show how decaying step sizes eliminate that stall and what constant a 1/k1/k schedule requires, before bounding the error that a constant step tuned to a fixed budget achieves on both convex and nonconvex losses. Finally, we show how to cancel the noise on a finite training set using a stored snapshot gradient. Three takeaways are worth keeping in mind throughout: the noise floor is proportional to the step size, a 1/k1/k schedule needs a large enough constant to achieve its rate, and a fixed budget of KK steps calls for a step size proportional to 1/K1/\sqrt{K}. The final subsection on variance reduction can be skipped on a first reading.

23.4.1 Minibatch Gradients#

23.4.1.1 The Cost of a Full Gradient#

A typical training objective averages the losses of nn examples,

f(x)=1n∑i=1nfi(x),f(\mathbf{x}) = \frac{1}{n} \sum_{i=1}^n f_i(\mathbf{x}),

where fif_i is the loss on example ii and x∈Rd\mathbf{x} \in \mathbb{R}^d holds the model parameters. Because its gradient ∇f=1n∑i∇fi\nabla f = \tfrac1n \sum_i \nabla f_i is also an average, evaluating it touches all nn examples. When n=109n = 10^9, a single step of gradient descent requires a full pass over the dataset, and gradient descent typically needs thousands of steps. Even on this chapter's running example, 12(x12+1000 x22)\tfrac12(x_1^2 + 1000\,x_2^2), whose curvatures differ by a factor of 10001000, the optimal fixed step requires about 7,0007{,}000 iterations to shrink the error a million-fold (Section 23.1). Stochastic gradient descent (SGD) avoids this cost by replacing the full average with the average over a random minibatch B\mathcal{B} of bb indices,

g^b(x)=1b∑i∈B∇fi(x),xk+1=xk−ηk g^b(xk).(23.4.1)\hat{\mathbf{g}}_b(\mathbf{x}) = \frac{1}{b} \sum_{i \in \mathcal{B}} \nabla f_i(\mathbf{x}), \qquad \mathbf{x}_{k+1} = \mathbf{x}_k - \eta_k\, \hat{\mathbf{g}}_b(\mathbf{x}_k). \tag{23.4.1}

Each step now inspects only bb examples instead of nn: a minibatch of b=256b = 256 out of 10910^9 examples is roughly four million times cheaper than a full pass. Throughout this section, kk indexes optimizer steps, and the step size ηk\eta_k may vary with kk. For our analysis, we draw a fresh minibatch at every step whose bb indices are independent and uniform on {1,…,n}\{1, \ldots, n\} (sampling with replacement). Real training loops usually shuffle the dataset and sample without replacement, which multiplies the gradient variance derived below by (n−b)/(n−1)(n-b)/(n-1)—a factor close to one whenever b≪nb \ll n (Section 9.2).

23.4.1.2 Unbiasedness and the 1/b1/b Law#

How accurate is a minibatch gradient? Two quantities capture its quality: its mean, which tells us whether it points in the right direction on average, and its mean squared distance from the true gradient, which we call its noise power. That noise power depends on how widely individual example gradients scatter around their mean, as measured by their covariance matrix.

Proposition (minibatch gradients are unbiased with noise power tr⁡Σ/b\operatorname{tr}\boldsymbol{\Sigma}/b). Fix x\mathbf{x} and let

Σ=1n∑i=1n(∇fi(x)−∇f(x))(∇fi(x)−∇f(x))⊤\boldsymbol{\Sigma} = \frac{1}{n} \sum_{i=1}^n \big(\nabla f_i(\mathbf{x}) - \nabla f(\mathbf{x})\big)\big(\nabla f_i(\mathbf{x}) - \nabla f(\mathbf{x})\big)^\top

be the covariance of a single uniformly drawn example gradient. If the bb indices of B\mathcal{B} are independent and uniform on {1,…,n}\{1, \ldots, n\}, then

E[g^b(x)]=∇f(x),E[∥g^b(x)−∇f(x)∥2]=tr⁡Σb.(23.4.2)\mathbb{E}\big[\hat{\mathbf{g}}_b(\mathbf{x})\big] = \nabla f(\mathbf{x}), \qquad \mathbb{E}\big[\|\hat{\mathbf{g}}_b(\mathbf{x}) - \nabla f(\mathbf{x})\|^2\big] = \frac{\operatorname{tr} \boldsymbol{\Sigma}}{b}. \tag{23.4.2}

Proof. For a single uniform index ii, E[∇fi(x)]=1n∑i∇fi(x)=∇f(x)\mathbb{E}[\nabla f_i(\mathbf{x})] = \tfrac1n \sum_i \nabla f_i(\mathbf{x}) = \nabla f(\mathbf{x}). Every term in the minibatch therefore has mean ∇f(x)\nabla f(\mathbf{x}), and so does their average. Because the bb indices are independent and each term has covariance Σ\boldsymbol{\Sigma}, the covariance of their sum is bΣb\boldsymbol{\Sigma}, and dividing by bb scales the covariance by 1/b21/b^2 to give Σ/b\boldsymbol{\Sigma}/b. Finally, the expected squared norm of any mean-zero random vector equals the trace of its covariance matrix. ■\blacksquare

During optimization, x\mathbf{x} is the current iterate xk\mathbf{x}_k and the minibatch is drawn independently of past steps, so both identities hold conditionally on xk\mathbf{x}_k. Note that unbiasedness depends on uniform sampling: if a sampler draws example ii with probability pip_i, each gradient must be reweighted by 1/(npi)1/(np_i) to keep the estimator unbiased.

Because the noise power decays like 1/b1/b, its root-mean-square amplitude decays only like 1/b1/\sqrt{b}: cutting the gradient noise in ten requires a hundred times as many examples per step. Meanwhile, the true gradient signal has squared norm ∥∇f∥2\|\nabla f\|^2 regardless of batch size. Signal and noise have equal power at the batch size bnoise=tr⁡Σ/∥∇f∥2b_{\textrm{noise}} = \operatorname{tr}\boldsymbol{\Sigma}/\|\nabla f\|^2, which the main text calls the gradient-noise scale (Section 9.8); exercise 1 derives its curvature-weighted counterpart.

To see how large this noise is on concrete data, we set up a small logistic-regression problem that we will reuse in the step-size experiment below. It has n=200n = 200 examples ai∈R5\mathbf{a}_i \in \mathbb{R}^5 with standard normal features, labels yi∈{−1,+1}y_i \in \{-1, +1\} generated from a logistic model with true weights (1,−2,1.5,0,2)(1, -2, 1.5, 0, 2), and the regularized loss

f(x)=1n∑i=1nlog⁡(1+e−yiai⊤x)+0.12∥x∥2.f(\mathbf{x}) = \frac{1}{n} \sum_{i=1}^n \log\big(1 + e^{-y_i \mathbf{a}_i^\top \mathbf{x}}\big) + \frac{0.1}{2} \|\mathbf{x}\|^2.

The quadratic penalty makes ff strongly convex with μ≥0.1\mu \ge 0.1. The gradient of example ii is ∇fi(x)=−yisiai+0.1 x\nabla f_i(\mathbf{x}) = -y_i s_i \mathbf{a}_i + 0.1\,\mathbf{x}, where si=1/(1+eyiai⊤x)s_i = 1/(1 + e^{y_i \mathbf{a}_i^\top \mathbf{x}}) is the probability that the model assigns to the wrong label. The cell below generates the dataset and defines the loss together with a vectorized helper returning all nn per-example gradients as the rows of an n×dn \times d matrix.

n, d, reg = 200, 5, 0.1                          # examples, parameters, l2 weight
x_true = np.array([1.0, -2.0, 1.5, 0.0, 2.0])
rng = np.random.default_rng()
A = rng.normal(size=(n, d))                       # row i: the features a_i
y = np.where(rng.random(n) < 1 / (1 + np.exp(-A @ x_true)), 1.0, -1.0)

def loss(x, A, y, reg):
    """The regularized logistic loss f(x)."""
    return np.mean(np.log1p(np.exp(-y * (A @ x)))) + 0.5 * reg * x @ x

def example_grads(x, A, y, reg):
    """The n x d matrix whose row i is the gradient of f_i at x."""
    s = 1 / (1 + np.exp(y * (A @ x)))             # probability of the wrong label
    return -(y * s)[:, None] * A + reg * x

Since the proposition is exact, simulation serves mainly as a sanity check and to show the actual scale of tr⁡Σ\operatorname{tr}\boldsymbol{\Sigma} on this problem. Below, we evaluate 10,00010{,}000 random minibatches of each size at x=0\mathbf{x} = \mathbf{0} and compare the empirical error against tr⁡Σ/b\operatorname{tr}\boldsymbol{\Sigma}/b.

G = example_grads(np.zeros(d), A, y, reg)        # per-example gradients at x = 0
g = G.mean(axis=0)                                # the full gradient
tr_sigma = ((G - g)**2).sum(axis=1).mean()
print(f'tr Sigma = {tr_sigma:.3f}')
for b in [1, 4, 16, 64]:
    idx = rng.integers(0, n, size=(10000, b))    # minibatches, with replacement
    err = ((G[idx].mean(axis=1) - g)**2).sum(axis=1).mean()
    print(f'b = {b:2d}: measured {err:.4f}, tr Sigma / b = {tr_sigma / b:.4f}, '
          f'ratio {err * b / tr_sigma:.3f}')
tr Sigma = 1.131
b =  1: measured 1.1188, tr Sigma / b = 1.1311, ratio 0.989
b =  4: measured 0.2847, tr Sigma / b = 0.2828, ratio 1.007
b = 16: measured 0.0699, tr Sigma / b = 0.0707, ratio 0.989
b = 64: measured 0.0177, tr Sigma / b = 0.0177, ratio 1.003

The single-example noise power tr⁡Σ\operatorname{tr}\boldsymbol{\Sigma} is about 1.11.1, and across all four batch sizes the measured error matches tr⁡Σ/b\operatorname{tr}\boldsymbol{\Sigma}/b to within a few percent of sampling fluctuation. Knowing the noise of a single step, we can now ask what that noise does over an entire optimization run.

23.4.1.3 The Noise Floor#

Does gradient noise average out over many steps, or does it accumulate? Section 9.2 measured the cloud in which SGD settles inside a valley and derived its radius. Here we solve the entire trajectory in closed form, which also tells us how many steps it takes to reach that cloud. The simplest case already contains the full mechanism: a single coordinate of a quadratic, f(x)=12λx2f(x) = \tfrac12 \lambda x^2 with curvature λ>0\lambda > 0 and minimizer 00. Model the stochastic gradient as the true gradient λxk\lambda x_k plus random noise ξk\xi_k with mean zero given xkx_k and variance σ2\sigma^2. Here σ2\sigma^2 plays the role of a diagonal entry of Σ/b\boldsymbol{\Sigma}/b, so every quantity proportional to σ2\sigma^2 scales as 1/b1/b. One SGD step reads

xk+1=xk−η (λxk+ξk)=ρ xk−η ξk,ρ=1−ηλ.x_{k+1} = x_k - \eta\,(\lambda x_k + \xi_k) = \rho\, x_k - \eta\, \xi_k, \qquad \rho = 1 - \eta\lambda.

At each step, the deterministic part pulls the iterate toward the minimizer by the factor ρ\rho, just as exact gradient descent does, while the stochastic part delivers a random kick −ηξk-\eta\xi_k. To track the iterate's size, we follow its second moment ek=E[xk2]e_k = \mathbb{E}[x_k^2]. Squaring the update and taking expectations, the cross term −2ρη E[xkξk]-2\rho\eta\,\mathbb{E}[x_k \xi_k] vanishes because ξk\xi_k has mean zero conditioned on xkx_k, leaving

ek+1=ρ2ek+η2σ2.e_{k+1} = \rho^2 e_k + \eta^2 \sigma^2.

Every step contracts the second moment by ρ2\rho^2 and injects fresh noise power η2σ2\eta^2\sigma^2. Nearly every result in this section can be read off this one recursion. A linear recurrence with a constant driving term is solved by finding its fixed point VV, where V=ρ2V+η2σ2V = \rho^2 V + \eta^2\sigma^2. Subtracting that fixed-point equation from the recursion shows that the remainder ek−Ve_k - V shrinks by ρ2\rho^2 at every step, giving

ek=V+ρ2k (e0−V)(23.4.3)e_k = V + \rho^{2k}\,(e_0 - V) \tag{23.4.3}

with the noise floor

V=η2σ21−ρ2=η σ2λ (2−ηλ)  ≈  η σ22λ(ηλ≪1).(23.4.4)V = \frac{\eta^2 \sigma^2}{1 - \rho^2} = \frac{\eta\, \sigma^2}{\lambda\, (2 - \eta\lambda)} \;\approx\; \frac{\eta\, \sigma^2}{2\lambda} \qquad (\eta\lambda \ll 1). \tag{23.4.4}

The floor grows linearly with the step size and the noise variance, and shrinks inversely with the curvature. Both formulas require 0<η<2/λ0 \lt \eta \lt 2/\lambda, the same stability ceiling as exact gradient descent on a quadratic; above it, the second moment diverges even without noise.

The trajectory splits cleanly into two phases. The transient ρ2k(e0−V)\rho^{2k}(e_0 - V) decays geometrically, just as in deterministic gradient descent, whereas the floor VV is purely an effect of noise. Far from the minimizer, the transient dominates and SGD behaves much like gradient descent. Close to the minimizer, the inward pull ηλx\eta\lambda x weakens while the random kicks keep the same variance η2σ2\eta^2\sigma^2, until the two balance at e=Ve = V. From then on the iterate never converges; instead, its distribution settles into a stationary noise ball around the minimizer whose root-mean-square radius, roughly ησ2/(2λ)\sqrt{\eta\sigma^2/(2\lambda)}, scales as η\sqrt{\eta}. Figure 23.4.1 illustrates both phases on a two-dimensional quadratic bowl.

Figure 23.4.1:

Gradient descent and fixed-step SGD on 12∥x∥2\tfrac12\|\mathbf{x}\|^2 with η=0.15\eta=0.15 and gradient noise of standard deviation 0.60.6. The full-batch path converges to the minimizer, whereas SGD descends like gradient descent and then fluctuates inside a noise ball. Dashed circles mark the noise ball at this step size and at half the step size; their radii, drawn at three times the per-coordinate root-mean-square distance ησ2/(2λ)\sqrt{\eta\sigma^2/(2\lambda)} to enclose the scatter, differ by a factor of 2\sqrt{2}.

In practice we care about the expected loss rather than the squared distance. Because Ef(xk)=12λek\mathbb{E} f(x_k) = \tfrac12 \lambda e_k, the loss floor is

12λV=η σ22 (2−ηλ)  ≈  η σ24.\tfrac12 \lambda V = \frac{\eta\, \sigma^2}{2\,(2 - \eta\lambda)} \;\approx\; \frac{\eta\, \sigma^2}{4}.

Surprisingly, for small steps the curvature λ\lambda cancels out completely: a flatter direction lets the iterate wander farther, by precisely the factor that its flatness discounts from the loss.

On a dd-dimensional quadratic, the coordinates along the eigenvectors of the Hessian decouple into dd independent copies of this scalar recursion, each with its own eigenvalue λi\lambda_i and noise variance σi2\sigma_i^2. The total expected loss floor is therefore the sum ∑iησi2/(2(2−ηλi))\sum_i \eta\sigma_i^2/(2(2 - \eta\lambda_i)). Because the σi2\sigma_i^2 are the diagonal entries of Σ/b\boldsymbol{\Sigma}/b in the eigenbasis, they sum to tr⁡Σ/b\operatorname{tr}\boldsymbol{\Sigma}/b. Whenever every ηλi≪1\eta\lambda_i \ll 1, the total loss floor simplifies to approximately ηtr⁡Σ/(4b)\eta\operatorname{tr}\boldsymbol{\Sigma}/(4b), which depends on the step size and batch size only through their ratio η/b\eta/b. Halving the step size and doubling the batch size therefore lower the floor by the same factor—the coupling behind the large-batch learning-rate rules in Section 9.8.

How quickly does a run reach its floor? Take λ=σ=1\lambda = \sigma = 1, as in the opening example, where η=0.1\eta = 0.1 produced V=0.053V = 0.053. Raising the step to η=0.3\eta = 0.3 raises the floor to V=0.176V = 0.176 (a little more than three times as high, with a loss floor of 0.0880.088). Starting from x0=3x_0 = 3 (e0=9e_0 = 9), the transient ek−Ve_k - V drops below a tenth of VV after 3636 steps at η=0.1\eta = 0.1 (ρ2=0.81\rho^2 = 0.81), compared with just 99 steps at η=0.3\eta = 0.3 (ρ2=0.49\rho^2 = 0.49). Cutting the step size to a third cuts the floor to roughly a third, but demands four times as many steps to reach it. Every method in the rest of this section is a different way of navigating this trade-off between speed and accuracy.

Now return to our running example 12(x12+1000 x22)\tfrac12(x_1^2 + 1000\,x_2^2), modeling the noise directly by adding independent mean-zero noise of variance σ2=1\sigma^2 = 1 to each coordinate of the gradient (x1,1000 x2)(x_1, 1000\,x_2) at every step. The two coordinates obey the scalar recursion with λ1=1\lambda_1 = 1 and λ2=1000\lambda_2 = 1000. Set η=1/L=10−3\eta = 1/L = 10^{-3}, half the stability ceiling 2/10002/1000. The stiff coordinate has ρ2=0\rho_2 = 0: a single step erases its transient completely, leaving it on its floor V2=10−3/1000=10−6V_2 = 10^{-3}/1000 = 10^{-6}. The slow coordinate has ρ1=0.999\rho_1 = 0.999 and floor V1=10−3/1.999=5.0×10−4V_1 = 10^{-3}/1.999 = 5.0 \times 10^{-4}, and its transient takes log⁡1000/(−2log⁡0.999)≈3,450\log 1000/(-2\log 0.999) \approx 3{,}450 steps to shrink a thousandfold. The total loss floor is 7.5×10−47.5 \times 10^{-4}, split between 2.5×10−42.5 \times 10^{-4} from the slow coordinate and 5×10−45 \times 10^{-4} from the stiff one. Notice the irony: the stiff coordinate that gradient descent eliminates in one step accounts for two-thirds of the loss floor, because at ηλ2=1\eta\lambda_2 = 1 its loss floor is ησ2/2\eta\sigma^2/2, twice the small-step value ησ2/4\eta\sigma^2/4. Ill-conditioning slows down the flat direction, while noise raises the loss along both.

Our closed-form floor is exact only for a quadratic with additive noise. Next, we test whether the scaling "floor proportional to η\eta" still holds on the non-quadratic logistic loss, and see how decaying step sizes break through the floor.

23.4.2 Step-Size Decay#

23.4.2.1 The Robbins--Monro Conditions#

Because the noise floor scales linearly with η\eta, actually reaching the minimizer requires shrinking the step size toward zero. Shrink it too fast, however, and the iterate stalls short of the goal: with unit-sized gradients, the total distance traveled cannot exceed ∑kηk\sum_k \eta_k. The classical conditions of Robbins and Monro (1951) capture both requirements at once,

∑kηk=∞,∑kηk2<∞.(23.4.5)\sum_{k} \eta_k = \infty, \qquad \sum_{k} \eta_k^2 \lt \infty. \tag{23.4.5}

The first condition guarantees that the iterate can travel arbitrarily far from its starting point, while the second keeps the cumulative variance injected by the noise, σ2∑kηk2\sigma^2 \sum_k \eta_k^2, finite. The schedule ηk=c/k\eta_k = c/k satisfies both conditions, whereas ηk=c/k\eta_k = c/\sqrt{k} and a constant step satisfy only the first. Together with unbiased gradients whose variance grows at most quadratically with the distance to the minimizer, these two conditions guarantee that SGD converges to the minimizer of any strongly convex loss (Robbins and Monro, 1951; Bottou et al., 2018).

On our scalar quadratic, convergence in mean square actually needs less. Unrolling the recursion shows that ek→0e_k \to 0 whenever ηk→0\eta_k \to 0 and ∑kηk=∞\sum_k \eta_k = \infty (with ηk<2/λ\eta_k \lt 2/\lambda); in particular, ηk=c/k\eta_k = c/\sqrt{k} yields ek≈cσ2/(2λk)e_k \approx c\sigma^2/(2\lambda\sqrt{k}), which simply tracks the instantaneous floor of the current step. The stronger square-summability condition is what the general theorem requires to guarantee convergence along almost every individual sample path.

Two questions remain for a non-quadratic objective: does the noise floor still scale linearly with η\eta, and does a decaying schedule push below it? To check on our logistic-regression problem, we first compute the reference optimum f⋆f^\star with 4,0004{,}000 full-gradient steps, then define a minibatch SGD loop that records the suboptimality gap f(xk)−f⋆f(\mathbf{x}_k) - f^\star at every step.

x_star = np.zeros(d)
for _ in range(4000):                             # full-gradient reference optimum
    x_star -= 0.5 * example_grads(x_star, A, y, reg).mean(axis=0)
f_star = loss(x_star, A, y, reg)

def sgd(schedule, A, y, reg, f_star, rng, steps=4000, b=8):
    """Minibatch SGD from x = 0; returns the gap f(x_k) - f* after every step."""
    x, gaps = np.zeros(A.shape[1]), np.empty(steps)
    for k in range(steps):
        idx = rng.integers(0, len(y), size=b)
        x -= schedule(k) * example_grads(x, A[idx], y[idx], reg).mean(axis=0)
        gaps[k] = loss(x, A, y, reg) - f_star
    return gaps

If the quadratic model is a reliable guide, halving a fixed step size should halve the gap at which SGD stalls. We run 4,0004{,}000 steps with b=8b = 8 using constant steps η=0.8\eta = 0.8 and η=0.4\eta = 0.4, alongside the decaying schedule ηk=80/(k+100)=0.8/(1+k/100)\eta_k = 80/(k + 100) = 0.8/(1 + k/100), which begins at 0.80.8. The cell prints the mean gap over the final 1,0001{,}000 steps of each run, reports the ratios between them, and plots 100100-step moving averages on log--log axes.

rules = {'fixed 0.8': lambda k: 0.8, 'fixed 0.4': lambda k: 0.4,
         'decay 0.8/(1+k/100)': lambda k: 0.8 / (1 + k / 100)}
gaps = {name: sgd(s, A, y, reg, f_star, rng) for name, s in rules.items()}
tail = [gap[-1000:].mean() for gap in gaps.values()]
print('mean gap, last 1000 steps: ' + ', '.join(f'{t:.1e}' for t in tail))
print(f'floor(0.8) / floor(0.4) = {tail[0] / tail[1]:.2f}, '
      f'floor(0.8) / decay = {tail[0] / tail[2]:.0f}')
window = np.ones(100) / 100                       # plot 100-step moving averages
d2l.plot(np.arange(100, 4001), [np.convolve(gap, window, 'valid') for gap in gaps.values()],
         'step k', 'f(x_k) - f*', xscale='log', yscale='log', legend=list(gaps))
mean gap, last 1000 steps: 1.4e-02, 5.9e-03, 4.1e-04
floor(0.8) / floor(0.4) = 2.35, floor(0.8) / decay = 34

Both fixed-step runs stall. At η=0.8\eta = 0.8, the mean gap over the last 1,0001{,}000 steps settles around 11 to 2×10−22 \times 10^{-2}, and halving the step size cuts it roughly in half: across repeated runs, the ratio fluctuates between about 1.71.7 and 2.82.8, centered on the factor of 22 predicted by the quadratic model even though the logistic loss is not quadratic. Meanwhile, the decaying schedule finishes roughly 2020 to 9090 times below the η=0.8\eta = 0.8 floor, and its curve on the log--log plot is still trending downward despite minibatch jitter. Its large early steps cover the distance to the minimizer quickly, while its small late steps shrink the noise ball.

23.4.2.2 The Constant in a 1/k1/k Schedule#

The schedule ηk=c/(k+k0)\eta_k = c/(k + k_0) satisfies both Robbins--Monro conditions for any c>0c > 0, with the shift k0k_0 keeping the initial steps safely below the stability ceiling. Does every choice of cc achieve an O(1/k)O(1/k) rate? The scalar quadratic with curvature λ=μ\lambda = \mu gives an exact answer. Writing t=k+k0t = k + k_0, the second-moment recursion becomes

ek+1=(1−cμt)2ek+c2σ2t2.e_{k+1} = \Big(1 - \frac{c\mu}{t}\Big)^2 e_k + \frac{c^2 \sigma^2}{t^2}.

Here the contraction weakens like 1/t1/t, while the injected noise power falls like 1/t21/t^2. Which effect dominates depends critically on cc: if cc is too small, the step size shrinks faster than the iterate can contract toward the minimizer, so the schedule itself becomes the bottleneck rather than the noise.

Proposition (the constant of a 1/k1/k schedule). On the scalar model with curvature μ\mu and step sizes ηk=c/(k+k0)\eta_k = c/(k + k_0), if 2cμ>12c\mu > 1 then k ek→Ak\, e_k \to A, where

A=c2σ22cμ−1.(23.4.6)A = \frac{c^2 \sigma^2}{2c\mu - 1}. \tag{23.4.6}

If 2cμ<12c\mu \lt 1, then eke_k decays like k−2cμk^{-2c\mu}, strictly slower than 1/k1/k, and at the boundary 2cμ=12c\mu = 1 it decays like log⁡k/k\log k / k. For every c>0c > 0, ek→0e_k \to 0.

We omit the full proof here, deriving the constant AA by matching leading terms and sketching the other two regimes informally; exercise 2 provides a complete proof by induction above the threshold and by unrolling the recursion below it.

Derivation of the constant. Try the asymptotic form ek≈A/te_k \approx A/t. The left-hand side of the recursion is A/(t+1)≈A/t−A/t2A/(t+1) \approx A/t - A/t^2. On the right-hand side, expanding (1−cμ/t)2≈1−2cμ/t(1 - c\mu/t)^2 \approx 1 - 2c\mu/t gives A/t−2cμA/t2+c2σ2/t2A/t - 2c\mu A/t^2 + c^2\sigma^2/t^2 up to terms of order t−3t^{-3}. The 1/t1/t terms match automatically, and equating the 1/t21/t^2 coefficients yields −A=−2cμA+c2σ2-A = -2c\mu A + c^2\sigma^2, or A(2cμ−1)=c2σ2A(2c\mu - 1) = c^2\sigma^2. Notice the subtle term on the left: advancing from tt to t+1t+1 contributes −A/t2-A/t^2, which is of the same order as the contraction term and creates the threshold 2cμ>12c\mu > 1. Ignoring that shift would falsely predict A=cσ2/(2μ)A = c\sigma^2/(2\mu) for every c>0c > 0.

Below the threshold (informally). When 2cμ<12c\mu \lt 1, the cumulative contraction sets the decay rate for both the initial error and the early noise. Because log⁡(1−u)≈−u\log(1 - u) \approx -u and ∑j≤t1/j≈log⁡t\sum_{j \le t} 1/j \approx \log t, the product of contractions behaves as ∏j(1−cμ/(j+k0))2≈(k0/t)2cμ\prod_{j}(1 - c\mu/(j + k_0))^2 \approx (k_0/t)^{2c\mu}, which decays more slowly than 1/t1/t. At the boundary 2cμ=12c\mu = 1, noise injected at step jj survives at step tt with weight roughly c2σ2/(jt)c^2\sigma^2/(jt), and summing over jj produces the extra log⁡k\log k factor.

To see the sensitivity in numbers, take μ=σ=1\mu = \sigma = 1. Setting c=1c = 1 gives A=1A = 1, and iterating the recursion from e0=1e_0 = 1 with k0=10k_0 = 10 yields k ek=1.0001k\, e_k = 1.0001 at k=106k = 10^6. Doubling to c=2c = 2 raises the constant only modestly, to A=4/3A = 4/3. Dropping below the threshold is far more damaging: c=0.25c = 0.25 yields a log--log slope of −0.50-0.50 between k=105k = 10^5 and 10610^6, and c=0.1c = 0.1 yields a slope of just −0.20-0.20. Minimizing AA over cc gives the optimal constant c=1/μc = 1/\mu, where A=σ2/μ2A = \sigma^2/\mu^2 and ek≈σ2/(μ2k)e_k \approx \sigma^2/(\mu^2 k). Remarkably, averaging the iterates of a constant-step run achieves the exact same optimal constant without decaying the step size at all (exercise 5). The sharp threshold at c=1/(2μ)c = 1/(2\mu) makes 1/k1/k schedules fragile in practice: the smallest curvature μ\mu is rarely known, and underestimating cc sacrifices the convergence rate itself. This fragility is one major reason practical learning-rate schedules decay more slowly than 1/k1/k.

On the running example 12(x12+1000 x22)\tfrac12(x_1^2 + 1000\,x_2^2), the shift k0k_0 creates a second difficulty. Stability at the very first step requires c/k0<2/Lc/k_0 \lt 2/L, or k0>cL/2k_0 > cL/2. Choosing the optimal constant c=1/μ=1c = 1/\mu = 1 for the slow coordinate therefore forces k0>500k_0 > 500. With k0=1000k_0 = 1000 and x0=(1,1)\mathbf{x}_0 = (1, 1), the slow coordinate's transient still retains a fraction (k0/(k+k0))2≈0.008(k_0/(k + k_0))^2 \approx 0.008 of its initial error after k=104k = 10^4 steps, leaving the expected loss at 4.2×10−34.2 \times 10^{-3}—more than five times worse than the constant-step floor of 7.5×10−47.5 \times 10^{-4}. The small initial steps demanded by the stiff coordinate starve the slow coordinate, and the condition number reappears inside k0k_0.

23.4.2.3 Schedule Shapes under the Exact Recursion#

Modern training rarely uses 1/k1/k decay; instead, practitioners favor cosine decay and warmup--stable--decay, which Section 9.7 compares on neural networks. Although no general theorem ranks those schedules on deep networks, our quadratic model lets us compute the expected loss of any schedule exactly, with no sampling and no random noise. Because our earlier derivation of the second-moment recursion holds step by step even when ηk\eta_k varies, we simply have

ek+1=(1−ηkλ)2ek+ηk2σ2,Ef(xk)=12λek.e_{k+1} = (1 - \eta_k \lambda)^2 e_k + \eta_k^2 \sigma^2, \qquad \mathbb{E} f(x_k) = \tfrac12 \lambda e_k.

Iterating this update computes the exact expected loss curve across a budget of KK steps in KK multiplications. We compare four shapes over the same budget KK, illustrated in Figure 23.4.2: a constant step η0\eta_0; the 1/k1/k schedule c/(k+k0)c/(k + k_0) with c=η0k0c = \eta_0 k_0 so that it also starts at η0\eta_0; cosine decay (Loshchilov and Hutter, 2016); and warmup--stable--decay (WSD) (Hu et al., 2024), which holds η0\eta_0 constant for the first 80%80\% of the budget and then decays linearly to zero:

ηkcos=12η0(1+cos⁡πkK),ηkWSD={η0,k<0.8K,η0 K−k0.2K,k≥0.8K.\begin{aligned} \eta_k^{\textrm{cos}} &= \tfrac12 \eta_0 \Big(1 + \cos\frac{\pi k}{K}\Big), \\ \eta_k^{\textrm{WSD}} &= \begin{cases} \eta_0, & k \lt 0.8K, \\ \eta_0\, \dfrac{K - k}{0.2K}, & k \ge 0.8K. \end{cases} \end{aligned}

Both cosine and WSD start at η0\eta_0 and end at zero, but cosine decays continuously throughout the run while WSD delays all decay until the final fifth. We omit the brief initial warmup ramp (discussed in Section 23.5.4) because the quadratic model is already stable at η0\eta_0 from step zero. WSD is popular in large-scale pretraining for an operational reason: any checkpoint from its constant plateau can be decayed to any chosen horizon, so the total budget need not be committed in advance. Our quadratic model evaluates final expected loss, not that flexibility.

Figure 23.4.2:

Schedule shapes over one budget KK: constant, the 1/k1/k decay (labelled c/kc/k), cosine, and warmup--stable--decay (WSD), each preceded by a short linear warmup omitted in the computation below. The figure plots the step-size sequences; the expected loss each produces on the quadratic model is computed below.

Which of these four schedules reaches the lowest final loss? It is worth guessing before running the numbers. The cell below iterates the exact recursion with λ=σ=1\lambda = \sigma = 1, K=2000K = 2000, η0=0.3\eta_0 = 0.3, x0=3x_0 = 3, and k0=50k_0 = 50 for the 1/k1/k schedule, printing the expected loss at 80%80\% of the budget and at the end before plotting Ef(xk)\mathbb{E} f(x_k).

lam, sigma, K, eta0, x0 = 1.0, 1.0, 2000, 0.3, 3.0

def expected_loss(schedule, lam, sigma, K, x0):
    """E f(x_k) = lam e_k / 2 for k = 1..K from the exact second-moment recursion."""
    e, Ef = x0**2, np.empty(K)
    for k in range(K):
        eta = schedule(k)
        e = (1 - eta * lam)**2 * e + eta**2 * sigma**2
        Ef[k] = 0.5 * lam * e
    return Ef

schedules = {
    'constant': lambda k: eta0,
    'c/k': lambda k: eta0 / (1 + k / 50),
    'cosine': lambda k: 0.5 * eta0 * (1 + np.cos(np.pi * k / K)),
    'WSD': lambda k: eta0 if k < 0.8 * K else eta0 * (K - k) / (0.2 * K)}
traces = {name: expected_loss(s, lam, sigma, K, x0) for name, s in schedules.items()}
print(f'floor {eta0 * sigma**2 / (2 * (2 - eta0 * lam)):.4f}   '
      + ''.join(f'{name:>10s}' for name in traces))
for label, k in [('E f at 80%', int(0.8 * K) - 1), ('E f at end', K - 1)]:
    print(f'{label:15s}' + ''.join(f'{Ef[k]:10.2e}' for Ef in traces.values()))
d2l.plot(np.arange(1, K + 1), list(traces.values()), 'step k', 'E f(x_k)',
         yscale='log', legend=list(traces))
floor 0.0882     constant       c/k    cosine       WSD
E f at 80%       8.82e-02  2.36e-03  7.87e-03  8.82e-02
E f at end       8.82e-02  1.90e-03  1.68e-03  6.13e-03

Because the recursion is deterministic, the numbers are identical on every run. The constant step settles within a tenth of its loss floor 0.08820.0882 by step 99 and stays there. WSD is the constant run until its decay phase begins, so at 80%80\% of the budget it sits on the exact same floor; its final 400400 steps then drop the loss by a factor of 14.414.4, down to 6.1×10−36.1 \times 10^{-3}, accounting for all of its gain. Cosine decay and 1/k1/k decay finish close together at 1.7×10−31.7 \times 10^{-3} and 1.9×10−31.9 \times 10^{-3}, roughly three to four times lower than WSD.

The 1/k1/k endpoint matches our proposition closely: here c=0.3⋅50=15c = 0.3 \cdot 50 = 15, giving A=225/29≈7.8A = 225/29 \approx 7.8 and Ef(xK)≈12A/(K+k0)=1.9×10−3\mathbb{E} f(x_K) \approx \tfrac12 A/(K + k_0) = 1.9 \times 10^{-3}. Keep in mind that this ranking is exact for these quadratic parameters and need not transfer directly to neural networks. On the quadratic itself, holding a constant plateau does not improve the final loss: lengthening WSD's decay phase reduces the final loss monotonically, reaching 2.7×10−32.7 \times 10^{-3} for a linear decay across the entire run.

23.4.3 Rates for a Fixed Budget#

A decaying schedule is built for an indefinite run. In practice, however, we usually know our compute budget KK ahead of time, which reframes the question: what constant step size should we choose for KK steps, and what accuracy does it guarantee? Without strong convexity, there is no geometric contraction factor and no exact noise floor, so we prove upper bounds rather than exact trajectories. Both bounds below share the same two-term structure: a transient term that decreases as 1/(ηK)1/(\eta K) plus a noise term that grows as η\eta. Balancing the two selects η∝1/K\eta \propto 1/\sqrt{K}, as shown in Figure 23.4.3.

Figure 23.4.3:

The two-term bound D2/(2ηK)+ηG2/2D^2/(2\eta K)+\eta G^2/2 of (23.4.7) plotted against the step size η\eta for D=G=1D=G=1 and two budgets. The transient falls with η\eta while the floor rises with it; their sum reaches its minimum DG/KDG/\sqrt{K} at η⋆=D/(GK)\eta^\star=D/(G\sqrt{K}), so a 100×100\times larger budget lowers both the optimal step and the bound by 10×10\times.

23.4.3.1 Averaged Iterates on Convex Losses#

Our first bound requires nothing beyond convexity, applied through the subgradient inequality of Section 23.3: f(y)≥f(x)+s⊤(y−x)f(\mathbf{y}) \ge f(\mathbf{x}) + \mathbf{s}^\top(\mathbf{y} - \mathbf{x}) for all y\mathbf{y} and every subgradient s∈∂f(x)\mathbf{s} \in \partial f(\mathbf{x}) (which reduces to ∇f(x)\nabla f(\mathbf{x}) wherever ff is differentiable).

Proposition (SGD on a convex loss, averaged iterate). Let ff be convex with a minimizer x⋆\mathbf{x}^\star and optimal value f⋆=f(x⋆)f^\star = f(\mathbf{x}^\star). Run xk+1=xk−η gk\mathbf{x}_{k+1} = \mathbf{x}_k - \eta\, \mathbf{g}_k from an initial point satisfying ∥x0−x⋆∥≤D\|\mathbf{x}_0 - \mathbf{x}^\star\| \le D, where each stochastic gradient satisfies E[gk∣xk]∈∂f(xk)\mathbb{E}[\mathbf{g}_k \mid \mathbf{x}_k] \in \partial f(\mathbf{x}_k) and E[∥gk∥2∣xk]≤G2\mathbb{E}[\|\mathbf{g}_k\|^2 \mid \mathbf{x}_k] \le G^2. Then the averaged iterate xˉK=1K∑k=0K−1xk\bar{\mathbf{x}}_K = \frac1K \sum_{k=0}^{K-1} \mathbf{x}_k satisfies

E[f(xˉK)]−f⋆  ≤  D22ηK+η G22,(23.4.7)\mathbb{E}\big[f(\bar{\mathbf{x}}_K)\big] - f^\star \;\le\; \frac{D^2}{2\eta K} + \frac{\eta\, G^2}{2}, \tag{23.4.7}

and choosing η=D/(GK)\eta = D/(G\sqrt{K}) gives E[f(xˉK)]−f⋆≤DG/K\mathbb{E}[f(\bar{\mathbf{x}}_K)] - f^\star \le DG/\sqrt{K}.

Proof. We track the squared distance to the minimizer. Expanding one update gives

∥xk+1−x⋆∥2=∥xk−x⋆∥2−2η gk⊤(xk−x⋆)+η2∥gk∥2.\|\mathbf{x}_{k+1} - \mathbf{x}^\star\|^2 = \|\mathbf{x}_k - \mathbf{x}^\star\|^2 - 2\eta\, \mathbf{g}_k^\top(\mathbf{x}_k - \mathbf{x}^\star) + \eta^2 \|\mathbf{g}_k\|^2.

Now take the conditional expectation given xk\mathbf{x}_k. Writing sk=E[gk∣xk]\mathbf{s}_k = \mathbb{E}[\mathbf{g}_k \mid \mathbf{x}_k], the cross term becomes −2η sk⊤(xk−x⋆)-2\eta\, \mathbf{s}_k^\top(\mathbf{x}_k - \mathbf{x}^\star). By the subgradient inequality at y=x⋆\mathbf{y} = \mathbf{x}^\star, sk⊤(xk−x⋆)≥f(xk)−f⋆\mathbf{s}_k^\top(\mathbf{x}_k - \mathbf{x}^\star) \ge f(\mathbf{x}_k) - f^\star. The entire argument hinges on this step: whenever the loss gap is large, the gradient aligns with the displacement from x⋆\mathbf{x}^\star and pulls the iterate closer. Bounding the final term by η2G2\eta^2 G^2, taking total expectations, and setting rk=E∥xk−x⋆∥2r_k = \mathbb{E}\|\mathbf{x}_k - \mathbf{x}^\star\|^2, we obtain

2η E[f(xk)−f⋆]  ≤  rk−rk+1+η2G2.2\eta\, \mathbb{E}\big[f(\mathbf{x}_k) - f^\star\big] \;\le\; r_k - r_{k+1} + \eta^2 G^2 .

Summing over k=0,…,K−1k = 0, \ldots, K-1 telescopes the distances, and since r0−rK≤r0≤D2r_0 - r_K \le r_0 \le D^2, we have 2η∑k<KE[f(xk)−f⋆]≤D2+Kη2G22\eta \sum_{k\lt K} \mathbb{E}[f(\mathbf{x}_k) - f^\star] \le D^2 + K\eta^2 G^2. Dividing by 2ηK2\eta K and applying Jensen's inequality to the convex function ff, f(xˉK)≤1K∑k<Kf(xk)f(\bar{\mathbf{x}}_K) \le \frac1K \sum_{k\lt K} f(\mathbf{x}_k), yields (23.4.7). The two terms match at η=D/(GK)\eta = D/(G\sqrt{K}), where each equals DG/(2K)DG/(2\sqrt{K}). ■\blacksquare

The meaning of the two terms is transparent: D2/(2ηK)D^2/(2\eta K) is the transient cost of traversing distance DD in KK steps of size η\eta, while ηG2/2\eta G^2/2 is the noise floor injected per step. Notably, the proof requires no smoothness at all, so the bound holds even for nonsmooth losses with corners such as the hinge loss. Multiplying the budget by 100100 reduces both the optimal step size and the guaranteed error by a factor of 1010. This O(1/K)O(1/\sqrt{K}) rate is unimprovable in the worst case: over the class of problems in the proposition, no algorithm that sees only unbiased stochastic gradients with E∥g∥2≤G2\mathbb{E}\|\mathbf{g}\|^2 \le G^2 can guarantee better than a constant multiple of DG/KDG/\sqrt{K} (Nemirovski and Yudin, 1983).

Adding strong convexity changes the scaling dramatically. On our scalar quadratic, the optimal constant step for a budget KK achieves eK=Θ(log⁡K/K)e_K = \Theta(\log K / K), because strong convexity shrinks the transient geometrically like ρ2K\rho^{2K} rather than algebraically like 1/(ηK)1/(\eta K).

Two caveats are worth noting. First, the proposition bounds the averaged iterate xˉK\bar{\mathbf{x}}_K; the final iterate obeys a weaker bound, and for the final iterate over a known budget the worst-case optimal schedule decays linearly to zero (Defazio et al., 2023). Second, the assumption E∥gk∥2≤G2\mathbb{E}\|\mathbf{g}_k\|^2 \le G^2 excludes unbounded-gradient losses such as a quadratic on all of Rd\mathbb{R}^d, though it holds for Lipschitz losses with bounded features (such as unregularized logistic regression) or whenever the iterates remain inside a bounded set. Because it is a worst-case bound, it can also be conservative on benign problems: on our logistic-regression task restricted to a ball, it overestimates the true gap by roughly an order of magnitude.

23.4.3.2 Random Iterates on Nonconvex Losses#

Neural networks confront us with nonconvex losses and noisy gradients at the same time, whereas our results so far have tackled one difficulty at a time. For a function ff whose gradient is LL-Lipschitz (an LL-smooth function), the loss surface lies everywhere below a tangent parabola of curvature LL:

f(y)  ≤  f(x)+∇f(x)⊤(y−x)+L2∥y−x∥2for all x,y.f(\mathbf{y}) \;\le\; f(\mathbf{x}) + \nabla f(\mathbf{x})^\top(\mathbf{y} - \mathbf{x}) + \frac{L}{2}\|\mathbf{y} - \mathbf{x}\|^2 \quad \textrm{for all } \mathbf{x}, \mathbf{y}.

With exact gradients and η=1/L\eta = 1/L, this quadratic upper bound yields min⁡k<K∥∇f(xk)∥2≤2LΔ/K\min_{k\lt K}\|\nabla f(\mathbf{x}_k)\|^2 \le 2L\Delta/K without any convexity assumption, where f⋆f^\star is a lower bound on ff and Δ=f(x0)−f⋆\Delta = f(\mathbf{x}_0) - f^\star (Section 23.1). With noisy gradients on a quadratic, a constant step stalls on a noise floor. The theorem of Ghadimi and Lan (2013) combines both ingredients. Model each SGD step as xk+1=xk−η gk\mathbf{x}_{k+1} = \mathbf{x}_k - \eta\, \mathbf{g}_k, where the stochastic gradient satisfies

E[gk∣xk]=∇f(xk),E[∥gk−∇f(xk)∥2∣xk]  ≤  σ2.(23.4.8)\mathbb{E}\left[\mathbf{g}_k \mid \mathbf{x}_k\right] = \nabla f(\mathbf{x}_k), \qquad \mathbb{E}\left[\|\mathbf{g}_k - \nabla f(\mathbf{x}_k)\|^2 \mid \mathbf{x}_k\right] \;\le\; \sigma^2. \tag{23.4.8}

In words, the stochastic gradient is unbiased and its noise power is uniformly bounded by σ2\sigma^2. By (23.4.2), a minibatch gradient satisfies both assumptions with σ2=sup⁡xtr⁡Σ(x)/b\sigma^2 = \sup_{\mathbf{x}} \operatorname{tr}\boldsymbol{\Sigma}(\mathbf{x})/b, provided that supremum is finite. It is finite for the bounded tanh⁡\tanh model below, though it is infinite for least squares on all of Rd\mathbb{R}^d, where the gradient noise grows with the distance from the minimizer.

Proposition (SGD finds approximate stationary points). Let ff be LL-smooth and bounded below by f⋆f^\star, set Δ=f(x0)−f⋆\Delta = f(\mathbf{x}_0) - f^\star, and run SGD with stochastic gradients satisfying (23.4.8) and a constant step size η≤1/L\eta \le 1/L. Then

1K∑k=0K−1E[∥∇f(xk)∥2]  ≤  2ΔηK+Lησ2,(23.4.9)\frac{1}{K} \sum_{k=0}^{K-1} \mathbb{E}\left[\|\nabla f(\mathbf{x}_k)\|^2\right] \;\le\; \frac{2\Delta}{\eta K} + L\eta\sigma^2, \tag{23.4.9}

and choosing η=min⁡(1/L, 2Δ/(Lσ2K))\eta = \min\bigl(1/L,\ \sqrt{2\Delta/(L\sigma^2 K)}\bigr) ensures that for an index RR drawn uniformly from {0,…,K−1}\{0, \ldots, K-1\} independently of the run,

E[∥∇f(xR)∥2]  ≤  2LΔK+2σ 2LΔK.(23.4.10)\mathbb{E}\left[\|\nabla f(\mathbf{x}_R)\|^2\right] \;\le\; \frac{2L\Delta}{K} + 2\sigma\,\sqrt{\frac{2L\Delta}{K}}. \tag{23.4.10}

Proof. Apply the LL-smoothness upper bound to the actual step y−x=−η gk\mathbf{y} - \mathbf{x} = -\eta\, \mathbf{g}_k:

f(xk+1)  ≤  f(xk)−η ∇f(xk)⊤gk+Lη22 ∥gk∥2.f(\mathbf{x}_{k+1}) \;\le\; f(\mathbf{x}_k) - \eta\, \nabla f(\mathbf{x}_k)^\top \mathbf{g}_k + \tfrac{L\eta^2}{2}\, \|\mathbf{g}_k\|^2.

Taking the conditional expectation given xk\mathbf{x}_k accomplishes two things at once: unbiasedness turns the middle term into −η ∥∇f(xk)∥2-\eta\,\|\nabla f(\mathbf{x}_k)\|^2, and the variance decomposition splits the quadratic term into signal plus noise, E[∥gk∥2∣xk]=∥∇f(xk)∥2+E[∥gk−∇f(xk)∥2∣xk]≤∥∇f(xk)∥2+σ2\mathbb{E}[\|\mathbf{g}_k\|^2 \mid \mathbf{x}_k] = \|\nabla f(\mathbf{x}_k)\|^2 + \mathbb{E}[\|\mathbf{g}_k - \nabla f(\mathbf{x}_k)\|^2 \mid \mathbf{x}_k] \le \|\nabla f(\mathbf{x}_k)\|^2 + \sigma^2. Collecting terms gives

E[f(xk+1)∣xk]  ≤  f(xk)−η(1−Lη2)∥∇f(xk)∥2+Lη2σ22.\mathbb{E}\left[f(\mathbf{x}_{k+1}) \mid \mathbf{x}_k\right] \;\le\; f(\mathbf{x}_k) - \eta\left(1 - \tfrac{L\eta}{2}\right) \|\nabla f(\mathbf{x}_k)\|^2 + \tfrac{L\eta^2 \sigma^2}{2}.

This is the standard descent lemma with one extra variance penalty 12Lη2σ2\tfrac12 L\eta^2\sigma^2 per step. Whenever η≤1/L\eta \le 1/L, we have 1−Lη2≥121 - \tfrac{L\eta}{2} \ge \tfrac12. Taking total expectations and summing over k=0,…,K−1k = 0, \ldots, K-1, the losses telescope to E[f(xK)]−f(x0)≥−Δ\mathbb{E}[f(\mathbf{x}_K)] - f(\mathbf{x}_0) \ge -\Delta; dividing both sides by ηK/2\eta K/2 yields (23.4.9). The left-hand side is precisely E[∥∇f(xR)∥2]\mathbb{E}[\|\nabla f(\mathbf{x}_R)\|^2] for a uniformly random index RR. Finally, for the balanced step size there are two cases. If 2Δ/(Lσ2K)≤1/L\sqrt{2\Delta/(L\sigma^2 K)} \le 1/L, the two terms in (23.4.9) are equal, each giving σ2LΔ/K\sigma\sqrt{2L\Delta/K}. Otherwise η=1/L\eta = 1/L and σ2<2LΔ/K\sigma^2 \lt 2L\Delta/K, so the bound is 2LΔ/K+σ2≤2LΔ/K+σ2LΔ/K2L\Delta/K + \sigma^2 \le 2L\Delta/K + \sigma\sqrt{2L\Delta/K}. Both cases are bounded by (23.4.10). ■\blacksquare

When σ=0\sigma = 0, the second term disappears and we recover the deterministic rate 2LΔ/K2L\Delta/K. When noise is present and the budget is large enough that K>2LΔ/σ2K > 2L\Delta/\sigma^2 (so η<1/L\eta \lt 1/L), the noise term dominates and decays only like K−1/2K^{-1/2}. With L=Δ=σ=1L = \Delta = \sigma = 1 and K=104K = 10^4, for instance, the balanced step is η≈0.014\eta \approx 0.014 and the bound reads 2×10−4+0.0282 \times 10^{-4} + 0.028—the noise term is 140140 times larger than the deterministic term. Notice also that this bound controls the squared gradient norm: multiplying the budget by 100100 reduces E∥∇f∥2\mathbb{E}\|\nabla f\|^2 by a factor of 1010, meaning that shrinking the gradient norm itself by a factor of 1010 requires 10410^4 times as many steps. If the gradient estimator is biased, an extra inner product survives the proof and adds a constant floor that never vanishes with KK (exercise 4).

Why does the theorem return a random iterate xR\mathbf{x}_R rather than the best one? With exact gradients, we observe ∥∇f(xk)∥\|\nabla f(\mathbf{x}_k)\| at every step and can simply pick the iterate with the smallest gradient. With stochastic gradients, the true gradient norm is hidden from the algorithm; picking an index RR uniformly at random is an implementable rule, and the time-average in (23.4.9) is exactly its expected squared gradient norm.

Compared with the convex case, two things changed: we bound the squared gradient norm instead of the loss gap, and we evaluate at a random iterate instead of the average. Without convexity, a small gradient is all a first-order method can certify, since a stationary point need not be a global minimizer. Like the convex bound, this K−1/2K^{-1/2} rate is worst-case optimal for any method given access only to stochastic gradients satisfying (23.4.8) (Arjevani et al., 2023).

23.4.3.3 The Rate on a Single tanh⁡\tanh Neuron#

Because the proposition is an upper bound, an experiment cannot prove that the rate is tight; it can only check how real runs behave relative to the K−1/2K^{-1/2} ceiling. Below, we measure both the random-iterate quantity and the best iterate on a small nonconvex problem—fitting a single tanh⁡\tanh neuron by least squares to n=64n = 64 noisy examples in five dimensions:

f(x)=1n∑i=1n(tanh⁡(ai⊤x)−yi)2.f(\mathbf{x}) = \frac1n \sum_{i=1}^n \big(\tanh(\mathbf{a}_i^\top \mathbf{x}) - y_i\big)^2 .

Each component is smooth and bounded, but none is convex because tanh⁡\tanh saturates into flat plateaus for large arguments. The cell below creates the data and defines a vectorized helper computing the exact full gradient for a batch of parameter vectors, one per row of X.

n_nc, d_nc = 64, 5                                # a small nonconvex problem
A_nc = rng.normal(size=(n_nc, d_nc))
y_nc = np.tanh(A_nc @ rng.normal(size=d_nc)) + 0.5 * rng.normal(size=n_nc)

def full_grad(X, A, y):
    """Exact gradient of mean_i (tanh(a_i^T x) - y_i)^2 at each row x of X."""
    t = np.tanh(X @ A.T)                          # (runs, n)
    return 2 * ((t - y) * (1 - t**2)) @ A / len(y)

We run single-example SGD for budgets K∈{125,500,2000,8000}K \in \{125, 500, 2000, 8000\} using the theorem's scaling η=0.5/K\eta = 0.5/\sqrt{K}, executing 2020 independent runs in parallel as the rows of X. For each budget, the cell records both the average of ∥∇f(xk)∥2\|\nabla f(\mathbf{x}_k)\|^2 across the run (the random-iterate metric) and its minimum (the best iterate), prints their log--log slopes against KK, and plots the random-iterate curve beside a reference slope of −1/2-1/2.

runs, Ks, avg, best = 20, np.array([125, 500, 2000, 8000]), [], []
for K in Ks:
    eta = 0.5 / np.sqrt(K)                        # the theorem's eta ~ 1/sqrt(K)
    X = np.zeros((runs, d_nc))                    # one row per independent run
    total, low = np.zeros(runs), np.full(runs, np.inf)
    for k in range(K):
        g2 = (full_grad(X, A_nc, y_nc)**2).sum(axis=1)   # |grad f(x_k)|^2
        total, low = total + g2, np.minimum(low, g2)
        i = rng.integers(0, n_nc, size=runs)             # one example per run
        t = np.tanh((X * A_nc[i]).sum(axis=1))
        X -= eta * (2 * (t - y_nc[i]) * (1 - t**2))[:, None] * A_nc[i]
    avg.append(total.mean() / K), best.append(low.mean())

def slope(v):
    return np.polyfit(np.log(Ks), np.log(v), 1)[0]

for name, v in [('random iterate', avg), ('best iterate', best)]:
    print(f'{name:15s}' + ' '.join(f'{u:.1e}' for u in v) + f'   slope {slope(v):.2f}')
d2l.plot(Ks, [avg, avg[0] * (Ks / Ks[0])**-0.5], 'budget K', 'E |grad f(x_R)|^2',
         xscale='log', yscale='log', legend=['random iterate', 'slope -1/2'])
random iterate 1.9e-01 8.3e-02 3.6e-02 1.7e-02   slope -0.58
best iterate   9.0e-03 2.1e-03 3.9e-04 4.9e-05   slope -1.25

Over a 6464-fold increase in budget, the random-iterate metric drops by a factor of about 1212 (typically between 99 and 1616 across runs), corresponding to a log--log slope near −0.6-0.6. That is slightly steeper than the theorem's −1/2-1/2 upper bound, as expected. The best iterate falls much faster—with a slope around −1-1 or steeper—but as noted above, an algorithm that sees only noisy gradients has no way to identify it.

23.4.4 Variance Reduction#

23.4.4.1 Control Variates#

Decaying the step size eliminates the noise floor by shrinking η\eta, but only by slowing progress to an algebraic rate. When the objective is a finite sum over nn examples, there is a second option: eliminate the gradient noise itself. At the minimizer x⋆\mathbf{x}^\star, the full gradient vanishes, yet the individual example gradients ∇fi(x⋆)\nabla f_i(\mathbf{x}^\star) generally do not—and those nonzero component gradients are the noise that a constant step size keeps injecting.

One important regime needs no remedy at all. If a model interpolates the training set (fitting every single example with zero loss), then every ∇fi(x⋆)\nabla f_i(\mathbf{x}^\star) vanishes at the minimizer, and constant-step SGD on a strongly convex objective converges linearly with no noise floor (exercise 6). Large neural networks often interpolate their training sets, which helps explain why constant-step SGD performs much better on them than the additive-noise floor predicts.

When the component gradients do not vanish at x⋆\mathbf{x}^\star, we must cancel their variance directly. A standard Monte Carlo trick does this: from the noisy estimator ∇fi(x)\nabla f_i(\mathbf{x}), subtract a correlated random variable whose exact mean we know, and add that mean back. Such a correction is called a control variate; we meet it again in the baseline of policy gradients (Section 14.8). On a finite sum, a natural control variate is the gradient ∇fi(x~)\nabla f_i(\tilde{\mathbf{x}}) of the same example evaluated at a saved snapshot x~\tilde{\mathbf{x}}, whose average over all ii is the full gradient ∇f(x~)\nabla f(\tilde{\mathbf{x}}), computed once per pass over the dataset. This yields the SVRG (stochastic variance-reduced gradient) estimator (Johnson and Zhang, 2013),

g~i(x)=∇fi(x)−∇fi(x~)+∇f(x~).(23.4.11)\tilde{\mathbf{g}}_i(\mathbf{x}) = \nabla f_i(\mathbf{x}) - \nabla f_i(\tilde{\mathbf{x}}) + \nabla f(\tilde{\mathbf{x}}). \tag{23.4.11}

In words, SVRG starts from the exact full gradient at the snapshot and adjusts it by how much a single example's gradient has changed between x~\tilde{\mathbf{x}} and x\mathbf{x}. For a uniformly drawn index ii, the estimator remains unbiased,

Ei[g~i(x)]=∇f(x)−∇f(x~)+∇f(x~)=∇f(x),\mathbb{E}_i\big[\tilde{\mathbf{g}}_i(\mathbf{x})\big] = \nabla f(\mathbf{x}) - \nabla f(\tilde{\mathbf{x}}) + \nabla f(\tilde{\mathbf{x}}) = \nabla f(\mathbf{x}),

while its variance shrinks to zero as the iterate and snapshot converge.

Proposition (SVRG variance is bounded by the distance to the snapshot). If each component fif_i has an LiL_i-Lipschitz gradient and Lmax⁡=max⁡iLiL_{\max} = \max_i L_i, then for a uniformly drawn index ii,

Ei∥g~i(x)−∇f(x)∥2  ≤  Ei∥∇fi(x)−∇fi(x~)∥2  ≤  Lmax⁡2 ∥x−x~∥2.(23.4.12)\mathbb{E}_i\big\|\tilde{\mathbf{g}}_i(\mathbf{x}) - \nabla f(\mathbf{x})\big\|^2 \;\le\; \mathbb{E}_i\big\|\nabla f_i(\mathbf{x}) - \nabla f_i(\tilde{\mathbf{x}})\big\|^2 \;\le\; L_{\max}^2\, \|\mathbf{x} - \tilde{\mathbf{x}}\|^2 . \tag{23.4.12}

Proof. The left-hand side is the variance of the random vector ∇fi(x)−∇fi(x~)\nabla f_i(\mathbf{x}) - \nabla f_i(\tilde{\mathbf{x}}), whose mean is ∇f(x)−∇f(x~)\nabla f(\mathbf{x}) - \nabla f(\tilde{\mathbf{x}}). Because the variance of any random vector is at most its second moment, the first inequality follows immediately. Applying the LiL_i-Lipschitz bound to each term of the second moment gives the second inequality. ■\blacksquare

Because the noise power is bounded by a multiple of ∥x−x~∥2\|\mathbf{x} - \tilde{\mathbf{x}}\|^2, it vanishes automatically as both x\mathbf{x} and x~\tilde{\mathbf{x}} approach x⋆\mathbf{x}^\star, removing the noise floor even for a constant step size. Intuitively, evaluating the same example at two nearby points produces gradients that share nearly identical noise; taking their difference cancels that shared noise while retaining the small genuine change in the gradient.

23.4.4.2 SVRG and SAGA#

To keep the bound (23.4.12) shrinking, the snapshot must periodically catch up to the iterate; yet recomputing a full gradient at every step would defeat the purpose of stochastic optimization. SVRG resolves this by running in epochs. At the beginning of each epoch, it saves the current iterate as the snapshot x~\tilde{\mathbf{x}} and computes its full gradient ∇f(x~)\nabla f(\tilde{\mathbf{x}}). It then performs mm inner updates x←x−η g~i(x)\mathbf{x} \leftarrow \mathbf{x} - \eta\, \tilde{\mathbf{g}}_i(\mathbf{x}) with fresh random indices, and sets the final inner iterate as the next snapshot. One epoch therefore costs n+2mn + 2m example-gradient evaluations. Johnson and Zhang (2013) (Theorem 1) prove that if every fif_i is convex with an Lmax⁡L_{\max}-Lipschitz gradient, ff is μ\mu-strongly convex, η<1/(4Lmax⁡)\eta \lt 1/(4L_{\max}), and mm is large enough that the per-epoch contraction factor falls below one, then the expected suboptimality E[f(x~)]−f⋆\mathbb{E}[f(\tilde{\mathbf{x}})] - f^\star decays geometrically with the number of epochs. (The theorem selects a random inner iterate as the next snapshot; our implementation uses the last iterate, which behaves similarly in practice.)

We test SVRG on ridge regression, a strongly convex finite sum with fi(x)=12(ai⊤x−yi)2+0.12∥x∥2f_i(\mathbf{x}) = \tfrac12(\mathbf{a}_i^\top\mathbf{x} - y_i)^2 + \tfrac{0.1}{2}\|\mathbf{x}\|^2, n=300n = 300 examples, and d=12d = 12 parameters. Its exact minimizer solves the normal equations, and each component gradient is LiL_i-Lipschitz with Li=∥ai∥2+0.1L_i = \|\mathbf{a}_i\|^2 + 0.1. The cell below generates the data, defines the component and full gradients, and prints Lmax⁡L_{\max} along with the theoretical step-size ceiling 1/(4Lmax⁡)1/(4L_{\max}).

n_r, d_r, reg_r = 300, 12, 0.1                    # ridge regression, a finite sum
A_r = rng.standard_normal((n_r, d_r))
y_r = A_r @ rng.standard_normal(d_r) + 0.5 * rng.standard_normal(n_r)
H_r = A_r.T @ A_r / n_r + reg_r * np.eye(d_r)     # Hessian of f
x_star_r = np.linalg.solve(H_r, A_r.T @ y_r / n_r)

def component_grad(x, i, A, y, reg):
    """Gradient of f_i(x) = (a_i^T x - y_i)^2 / 2 + reg |x|^2 / 2 (i: index or array)."""
    return A[i] * (A[i] @ x - y[i])[..., None] + reg * x

def full_grad_sum(x, A, y, reg):
    """Gradient of the finite sum f = mean_i f_i."""
    return A.T @ (A @ x - y) / len(y) + reg * x

def objective(x, A, y, reg):
    """The ridge objective f(x)."""
    return 0.5 * np.mean((A @ x - y)**2) + 0.5 * reg * x @ x

L_max = (A_r**2).sum(axis=1).max() + reg_r       # largest per-example smoothness
print(f'L_max = {L_max:.0f}, 1 / (4 L_max) = {1 / (4 * L_max):.4f}')
L_max = 29, 1 / (4 L_max) = 0.0088

Across random draws of the data, Lmax⁡L_{\max} is typically between 2525 and 4040, putting the theorem's step-size ceiling 1/(4Lmax⁡)1/(4L_{\max}) between roughly 0.0060.006 and 0.010.01.

Next, we compare SVRG (m=nm = n) against single-example SGD at the same constant step size η=0.02\eta = 0.02 (more than twice the theorem's bound) for 1212 epochs costing 3n3n example-gradient evaluations each. We also test our earlier quadratic-floor formula on SGD: its steady-state loss gap should equal the sum of ησi2/(2(2−ηλi))\eta\sigma_i^2/(2(2 - \eta\lambda_i)) over the eigenvectors of the Hessian, where σi2\sigma_i^2 is the variance of the example gradients at x⋆\mathbf{x}^\star along eigenvector ii.

eta, epochs = 0.02, 12
f_star_r = objective(x_star_r, A_r, y_r, reg_r)
snap, gaps_svrg = np.zeros(d_r), []
for _ in range(epochs):                           # n + 2n example gradients per epoch
    g_snap = full_grad_sum(snap, A_r, y_r, reg_r)
    x = snap.copy()
    for i in rng.integers(0, n_r, size=n_r):
        x -= eta * (component_grad(x, i, A_r, y_r, reg_r)
                    - component_grad(snap, i, A_r, y_r, reg_r) + g_snap)
    snap = x
    gaps_svrg.append(objective(snap, A_r, y_r, reg_r) - f_star_r)
x, gaps_sgd = np.zeros(d_r), []
for _ in range(epochs):
    for i in rng.integers(0, n_r, size=3 * n_r):  # the same 3n budget per epoch
        x -= eta * component_grad(x, i, A_r, y_r, reg_r)
    gaps_sgd.append(objective(x, A_r, y_r, reg_r) - f_star_r)
G_r = component_grad(x_star_r, np.arange(n_r), A_r, y_r, reg_r)  # noise at x*
ev, Q = np.linalg.eigh(H_r)                       # Hessian eigenvalues, eigenvectors
s2 = ((G_r @ Q)**2).mean(axis=0)                  # noise variance per eigenvector
floor = (eta * s2 / (2 * (2 - eta * ev))).sum()   # the loss floors add
print(f'SGD: predicted floor {floor:.1e}, mean gap in epochs 4-12 '
      f'{np.mean(gaps_sgd[3:]):.1e}')
print('SVRG: gap after epochs 1, 4, 12: '
      + ', '.join(f'{gaps_svrg[e - 1]:.0e}' for e in (1, 4, 12)))
d2l.plot(np.arange(1, epochs + 1), [gaps_sgd, gaps_svrg], 'epoch (3n gradients)',
         'f(x) - f*', yscale='log', legend=['SGD', 'SVRG'])
SGD: predicted floor 1.9e-02, mean gap in epochs 4-12 2.0e-02
SVRG: gap after epochs 1, 4, 12: 4e-01, 7e-04, 3e-11

SGD drops rapidly at first and then plateaus at a few times 10−210^{-2}, right where our floor formula predicts. Across runs, the measured plateau falls between roughly 10%10\% below and 40%40\% above the prediction—slightly above more often than below, because the formula evaluates gradient variance only at x⋆\mathbf{x}^\star, whereas the example gradients spread slightly more away from the minimizer. SVRG starts behind and finishes far ahead. After its first epoch (which takes only nn inner steps anchored at the starting point), its gap still exceeds SGD's. From epoch 22 onward, however, it shrinks by roughly a factor of eight per epoch (between five and thirteen across runs), reaching 10−1310^{-13} to 10−810^{-8} by epoch 1212. Notably, it achieves this linear convergence at a step size more than twice the theorem's limit, showing that the theoretical step condition is sufficient rather than necessary. Keep in mind the three assumptions behind this win: a finite sum, multiple passes over it, and strong convexity for the linear rate. On streaming data, where each example is seen only once, there is no finite sum to snapshot.

SAGA (Defazio et al., 2014) avoids periodic full passes altogether by replacing the snapshot with a table t1,…,tn\mathbf{t}_1, \ldots, \mathbf{t}_n storing the most recent gradient evaluated for each example. At each step it forms the estimator ∇fi(x)−ti+1n∑jtj\nabla f_i(\mathbf{x}) - \mathbf{t}_i + \tfrac1n\sum_j \mathbf{t}_j and then overwrites ti\mathbf{t}_i with ∇fi(x)\nabla f_i(\mathbf{x}). SAGA computes only one new example gradient per step, at the price of storing n×dn \times d numbers (or just one scalar per example for generalized linear models; see exercise 3).

On deep neural networks, unfortunately, neither SVRG nor SAGA has delivered consistent gains: the control variate quickly goes stale when the loss landscape shifts rapidly or when data augmentation perturbs each example on every pass. Meanwhile, a second limitation has been with us since the ill-conditioned valley: every method in this section applies a single global step size to all coordinates, forcing the stiffest direction of our running example to cap η\eta at 2/10002/1000. In the next section, we remove that bottleneck by letting each coordinate adapt its own step size from the gradients it has observed.

23.4.5 Summary#

A minibatch gradient of size bb is an unbiased estimator of ∇f\nabla f whose noise power is tr⁡Σ/b\operatorname{tr}\boldsymbol{\Sigma}/b. On a quadratic, a fixed step size η\eta drives the second moment of each coordinate geometrically at rate (1−ηλ)2(1 - \eta\lambda)^2 onto the noise floor ησ2/(λ(2−ηλ))\eta\sigma^2/(\lambda(2 - \eta\lambda)), and the per-coordinate loss floors ησ2/(2(2−ηλ))\eta\sigma^2/(2(2 - \eta\lambda)) add up across dimensions. Because the floor grows linearly with η\eta while the transient shrinks faster at larger η\eta, no constant step reaches the minimizer, and every technique in this section manages that trade-off. A Robbins--Monro schedule removes the floor, with ηk=c/k\eta_k = c/k achieving O(1/k)O(1/k) only when c>1/(2μ)c > 1/(2\mu). Over a fixed budget of KK steps, a constant step η∝1/K\eta \propto 1/\sqrt{K} guarantees DG/KDG/\sqrt{K} for the averaged iterate on convex losses and O(σLΔ/K)O(\sigma\sqrt{L\Delta/K}) for the expected squared gradient at a random iterate on smooth nonconvex losses. Finally, on a finite sum, the SVRG control variate stays unbiased with variance at most Lmax⁡2∥x−x~∥2L_{\max}^2\|\mathbf{x} - \tilde{\mathbf{x}}\|^2, allowing a fixed step size to converge linearly on strongly convex problems.

23.4.6 Exercises#

  1. [code] Noise scale and critical batch size. ● How much does one minibatch step lower the loss, and how does the gain depend on bb? Write g=∇f(x)\mathbf{g} = \nabla f(\mathbf{x}) and H=∇2f(x)\mathbf{H} = \nabla^2 f(\mathbf{x}), and approximate the loss after the step x−η g^b\mathbf{x} - \eta\,\hat{\mathbf{g}}_b of (23.4.1) by its second-order Taylor expansion at x\mathbf{x}. The analysis follows McCandlish et al. (2018).
    1. Use the covariance Σ/b\boldsymbol{\Sigma}/b of g^b\hat{\mathbf{g}}_b, established in the proof of (23.4.2), to show that the expected loss after the step is minimized by ηopt(b)=ηmax⁡/(1+Bnoise/b)\eta_{\textrm{opt}}(b) = \eta_{\max} / (1 + B_{\textrm{noise}}/b), with expected improvement Δmax⁡/(1+Bnoise/b)\Delta_{\max} / (1 + B_{\textrm{noise}}/b), where
ηmax⁡=∥g∥2g⊤Hg,Δmax⁡=∥g∥42 g⊤Hg,Bnoise=tr⁡(HΣ)g⊤Hg.\eta_{\max} = \frac{\|\mathbf{g}\|^2}{\mathbf{g}^\top \mathbf{H} \mathbf{g}}, \qquad \Delta_{\max} = \frac{\|\mathbf{g}\|^4}{2\,\mathbf{g}^\top \mathbf{H} \mathbf{g}}, \qquad B_{\textrm{noise}} = \frac{\operatorname{tr}(\mathbf{H} \boldsymbol{\Sigma})}{\mathbf{g}^\top \mathbf{H} \mathbf{g}}.
  1. The linear scaling rule of Goyal et al. (2017) multiplies η\eta by the same factor as bb. For which batch sizes does this rule follow from ηopt(b)\eta_{\textrm{opt}}(b)? What does a larger batch gain per step once b≫Bnoiseb \gg B_{\textrm{noise}}?
  2. For H\mathbf{H} proportional to the identity, BnoiseB_{\textrm{noise}} reduces to Bsimple=tr⁡Σ/∥g∥2B_{\textrm{simple}} = \operatorname{tr}\boldsymbol{\Sigma} / \|\mathbf{g}\|^2, the gradient-noise scale bnoiseb_{\textrm{noise}} of the text. Compute BsimpleB_{\textrm{simple}} and BnoiseB_{\textrm{noise}} for the logistic-regression problem of this section at x=0\mathbf{x} = \mathbf{0} and after 55, 1010, and 2020 full-gradient steps with η=0.5\eta = 0.5, using example_grads and the Hessian H(x)=1n∑isi(1−si) aiai⊤+0.1 I\mathbf{H}(\mathbf{x}) = \frac1n \sum_i s_i(1 - s_i)\,\mathbf{a}_i \mathbf{a}_i^\top + 0.1\,\mathbf{I} with si=1/(1+eyiai⊤x)s_i = 1/(1 + e^{y_i \mathbf{a}_i^\top \mathbf{x}}). How does the noise scale change as the iterates approach the optimum? Treat BnoiseB_{\textrm{noise}} as the critical batch size that separates the two regimes of (b). How should the batch size change over a training run?
  1. [code] The constant in a 1/k1/k schedule. ●● The text found the constant AA of (23.4.6) to leading order. This exercise makes it rigorous and carries it to the running example.

    1. Let t=k+k0t = k + k_0 and suppose uk+1≤(1−a/t) uk+q/t2u_{k+1} \le (1 - a/t)\, u_k + q/t^2 for all k≥0k \ge 0, with a>1a > 1, q>0q > 0, uk≥0u_k \ge 0 and k0≥ak_0 \ge a. Prove by induction that uk≤ν/(k+k0)u_k \le \nu/(k + k_0) with ν=max⁡{q/(a−1), k0u0}\nu = \max\{q/(a - 1),\ k_0 u_0\}. (Hint: 1−a/t≥01 - a/t \ge 0, and 1/t−1/t2≤1/(t+1)1/t - 1/t^2 \le 1/(t + 1).)
    2. Apply the lemma to the recursion ek+1=(1−cμ/t)2ek+c2σ2/t2e_{k+1} = (1 - c\mu/t)^2 e_k + c^2\sigma^2/t^2. Show that (1−cμ/t)2≤1−(2cμ−(cμ)2/k0)/t(1 - c\mu/t)^2 \le 1 - (2c\mu - (c\mu)^2/k_0)/t for t≥k0t \ge k_0, so that any 2cμ>12c\mu > 1 gives ek=O(1/k)e_k = O(1/k) once k0k_0 is large enough. Identify aa and qq, and show that q/(a−1)→Aq/(a - 1) \to A as k0→∞k_0 \to \infty.
    3. For 2cμ<12c\mu \lt 1, show ek=Θ(k−2cμ)e_k = \Theta(k^{-2c\mu}) from the product ∏j<k(1−cμ/(j+k0))2\prod_{j\lt k}(1 - c\mu/(j + k_0))^2 and the unrolled noise sum.
    4. Iterate the recursion with μ=σ=1\mu = \sigma = 1, k0=10k_0 = 10 and e0=1e_0 = 1 up to k=106k = 10^6 for c∈{0.1,0.25,0.5,1,2}c \in \{0.1, 0.25, 0.5, 1, 2\}. Report the log–log slope between k=105k = 10^5 and 10610^6 and the value of k ekk\, e_k at 10610^6. Which costs more, a constant twice the minimizer of AA or half of it?
    5. On the running example 12(x12+1000 x22)\tfrac12(x_1^2 + 1000\,x_2^2) with unit noise per coordinate, stability at the first step forces c/k0<2/1000c/k_0 \lt 2/1000. Take c=1/μ=1c = 1/\mu = 1, k0=1000k_0 = 1000, x0=(1,1)\mathbf{x}_0 = (1, 1) and K=104K = 10^4. Compute the expected loss by the two-coordinate recursion (it is about 4.2×10−34.2 \times 10^{-3}) and compare it with the constant step η=10−3\eta = 10^{-3} (7.5×10−47.5 \times 10^{-4}) and with cosine decay from the same η0\eta_0 (1.0×10−41.0 \times 10^{-4}). Which coordinate does the 1/k1/k decay starve, and why does the condition number reappear in k0k_0?
  2. [code] SVRG inner loop and SAGA. Use the ridge data and the functions component_grad, full_grad_sum and objective of this section with a budget of 36n=10,80036n = 10{,}800 example-gradient evaluations, the budget behind the 1212 reported epochs of the SVRG cell. Measure each run by the number of evaluations it needs to bring the gap below 10−1010^{-10}, checking once per epoch.

    1. Let the inner loop run mm steps, so that one epoch costs n+2mn + 2m evaluations, and vary m∈{10,30,75,300,1200}m \in \{10, 30, 75, 300, 1200\} at η∈{0.01,0.02}\eta \in \{0.01, 0.02\}. Which mm is best at each step size? Explain the trade-off between amortizing the snapshot gradient and letting the control variate go stale, and why the best mm moves with η\eta.
    2. Implement SAGA: keep a table with the most recent gradient of every example, filled at x0\mathbf{x}_0 for nn evaluations, and use ∇fi(x)−ti+1n∑jtj\nabla f_i(\mathbf{x}) - \mathbf{t}_i + \tfrac1n \sum_j \mathbf{t}_j as the estimator, where ti\mathbf{t}_i is the table entry of example ii. Compare SAGA with the best SVRG run at both step sizes. How many numbers does the table hold for this problem, and how many would suffice if you stored only the scalar ai⊤x−yi\mathbf{a}_i^\top\mathbf{x} - y_i per example?
  3. Biased gradient estimators. ● Keep the variance bound of (23.4.8), now measured around the conditional mean, but replace unbiasedness by E[gk∣xk]=∇f(xk)+δk\mathbb{E}[\mathbf{g}_k \mid \mathbf{x}_k] = \nabla f(\mathbf{x}_k) + \boldsymbol{\delta}_k with ∥δk∥≤δ\|\boldsymbol{\delta}_k\| \le \delta.

    1. Redo the proof of (23.4.9) for η≤1/L\eta \le 1/L and show
1K∑k=0K−1E[∥∇f(xk)∥2]  ≤  2ΔηK+Lησ2+δ2.(23.4.13)\frac{1}{K} \sum_{k=0}^{K-1} \mathbb{E}\left[\|\nabla f(\mathbf{x}_k)\|^2\right] \;\le\; \frac{2\Delta}{\eta K} + L\eta\sigma^2 + \delta^2. \tag{23.4.13}

Use Lη≤1L\eta \le 1 on the term Lη22∥∇f(xk)+δk∥2\tfrac{L\eta^2}{2}\|\nabla f(\mathbf{x}_k) + \boldsymbol{\delta}_k\|^2 before expanding it.

  1. Show that the term δ2\delta^2 cannot be removed: give a one-dimensional ff and a constant bias for which SGD with σ=0\sigma = 0 converges to a point where ∣f′∣2=δ2|f'|^2 = \delta^2.
  2. A single minibatch drawn uniformly without replacement is still an unbiased estimator of the full gradient. Which of the following estimators are biased in this sense: the example gradient at a step of random reshuffling (Section 9.2), which visits every example once per epoch in a fresh random order; a stochastic gradient clipped to a fixed maximum norm; the gradient evaluated at the iterate of τ\tau steps earlier, as in asynchronous training?
  1. [code] Iterate averaging. ● Polyak and Juditsky (1992) showed that averaging the iterates of a slowly decaying or constant-step run reaches the best possible constant. Consider the scalar model with a constant step η∈(0,2/λ)\eta \in (0, 2/\lambda), started in its stationary distribution.

    1. Show that Cov(xj,xk)=Vρ∣j−k∣\textrm{Cov}(x_j, x_k) = V\rho^{|j - k|}.
    2. Show that the average xˉK=1K∑k<Kxk\bar{x}_K = \frac1K \sum_{k\lt K} x_k has E[xˉK2]=VK⋅1+ρ1−ρ−O(K−2)\mathbb{E}[\bar{x}_K^2] = \frac{V}{K}\cdot\frac{1 + \rho}{1 - \rho} - O(K^{-2}), and that V(1+ρ)/(1−ρ)=σ2/λ2V(1 + \rho)/(1 - \rho) = \sigma^2/\lambda^2 for every such η\eta: to leading order the averaged iterate does not depend on the step.
    3. Check by simulation with K=2000K = 2000 and 4,0004{,}000 runs at η=0.3\eta = 0.3 and η=0.1\eta = 0.1, with λ=σ=1\lambda = \sigma = 1. You should find E[xˉK2]≈5×10−4\mathbb{E}[\bar{x}_K^2] \approx 5 \times 10^{-4} in both cases, against last-iterate floors of 0.180.18 and 0.0530.053.
    4. Started at x0=3x_0 = 3 instead, the average remembers the transient. Show that its contribution to E[xˉK2]\mathbb{E}[\bar{x}_K^2] is about (x0/(ηλK))2(x_0/(\eta\lambda K))^2, and decide when averaging only the second half of the run is better.
    5. Compare with the best 1/k1/k schedule, whose constant is A=σ2/μ2A = \sigma^2/\mu^2. What does each of the two routes to the rate σ2/(μ2K)\sigma^2/(\mu^2 K) require?
  2. [code] Interpolation and linear convergence. ●● Suppose each fif_i is convex with an LiL_i-Lipschitz gradient, ff is μ\mu-strongly convex, and every fif_i is minimized at the same point x⋆\mathbf{x}^\star, as when a model fits every training example exactly. The analysis follows Vaswani et al. (2019).

    1. Show that Ei∥∇fi(x)∥2≤2Lmax⁡(f(x)−f⋆)\mathbb{E}_i\|\nabla f_i(\mathbf{x})\|^2 \le 2L_{\max}(f(\mathbf{x}) - f^\star). (Hint: a convex LL-smooth hh minimized at x⋆\mathbf{x}^\star satisfies ∥∇h(x)∥2≤2L(h(x)−h(x⋆))\|\nabla h(\mathbf{x})\|^2 \le 2L(h(\mathbf{x}) - h(\mathbf{x}^\star)).)
    2. Deduce that single-example SGD with a constant η≤1/Lmax⁡\eta \le 1/L_{\max} satisfies E∥xk+1−x⋆∥2≤(1−ημ) E∥xk−x⋆∥2\mathbb{E}\|\mathbf{x}_{k+1} - \mathbf{x}^\star\|^2 \le (1 - \eta\mu)\,\mathbb{E}\|\mathbf{x}_k - \mathbf{x}^\star\|^2: linear convergence with no floor. What is tr⁡Σ(x⋆)\operatorname{tr}\boldsymbol{\Sigma}(\mathbf{x}^\star) in this case?
    3. Check it on least squares with n=50n = 50 examples and d=100d = 100 parameters, η=1/Lmax⁡\eta = 1/L_{\max} and x0=0\mathbf{x}_0 = \mathbf{0}. The iterates stay in the row space of A\mathbf{A}, where ff is strongly convex, so (b) applies there. Show that the gap falls linearly with consistent labels and also with labels corrupted by noise of standard deviation 0.50.5, and explain why the noise does not matter here.
    4. Repeat with n=200n = 200 and d=100d = 100. Now the noisy labels bring the floor back. Why?

Discussions