Module contents
Lesson 19 of 27Advanced 120 min

SGD in depth: nonconvexity, momentum, learning-rate schedules and variance reduction

Extend SGD analysis to practical settings: convergence to stationary points in nonconvex problems, stochastic momentum, learning-rate schedules (decay, cosine, warmup and WSD), and SVRG and SAGA variance reduction, which recover linear convergence for finite sums.

After this lesson you can

  • Prove SGD's rate toward stationary points for nonconvex L-smooth functions (Ghadimi and Lan).
  • Analyze SGD with momentum as an exponential gradient average and calculate its effective step.
  • Justify step decay theoretically and explain the roles of warmup, cosine and warmup-stable-decay.
  • Implement SVRG and SAGA and prove why their variance vanishes at the optimum.
  • Design an experiment comparing learning-rate schedules under a fixed compute budget.

Before you start

Motivation: what convex theory does not explain

The previous lesson left SGD in a clean state: with Robbins–Monro steps on a convex problem, error falls as O(1/k)\bigO(1/\sqrt{k}), or O(1/k)\bigO(1/k) with strong convexity (convex SGD convergence), and iterate averaging removes remaining noise. Now open a modern network’s training script, for example a GPT’s:

opt = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9)       # o AdamW
sched = warmup_lineal(2000) + coseno_hasta(total_steps)               # o WSD
for step in range(total_steps):
    loss = model(batch).loss; loss.backward(); opt.step(); sched.step()

None of this fits that analysis. The loss is nonconvex. The step does not decay as 1/k1/k: it rises for thousands of steps, stays high and finally plunges. There is inertia β=0.9\beta = 0.9 nobody justifies. And variance-reduction methods, which turn SGD’s O(1/k)\bigO(1/k) into linear convergence for finite sums and were central to machine-learning optimization from 2012 to 2018, appear in no serious training script.

This lesson explains each piece with provable results:

  • Nonconvex SGD. We cannot promise a global minimum, but can promise something concrete: the average gradient becomes small at rate O(T−1/2)\bigO(T^{-1/2}), the best possible rate for any stochastic first-order method under these assumptions.
  • Stochastic momentum. It is an exponential moving-average filter with hidden gain 1/(1−β)1/(1 - \beta): when noise dominates, SGD with momentum behaves like SGD with step η/(1−β)\eta/(1 - \beta).
  • Learning-rate schedules. Stationary SGD loss is proportional to step size. Everything follows: why learning rate falls at the end, why loss falls in steps, why WSD works as well as cosine, and why warmup avoids early divergence.
  • Variance reduction. SVRG and SAGA make estimator variance vanish at the optimum and recover linear convergence. We prove this and see why they seldom help network training.

SGD on nonconvex functions

In a nonconvex problem asking for f(xk)→f⋆f(\vb{x}_k) \to f^\star makes no sense: deterministic gradient descent can already stop at a local minimum or saddle point. What does make sense, and what lesson 8 proved for the deterministic case (nonconvex stationarity), is measuring progress by gradient norm: a point with ∥∇f(x)∥≤ε\norm{\grad f(\vb{x})} \le \eps is an ε\eps-stationary point.

This is nonconvex SGD convergence. The proof takes four lines from the descent lemma and you will do it step by step in the first exercise. The idea: an SGD step decreases ff in expectation by at least η2∥∇f∥2\frac{\eta}{2}\norm{\grad f}^2 and increases it by at most Lη22σ2\frac{L\eta^2}{2}\sigma^2 due to noise. Summing TT steps, total decrease cannot exceed budget Δ=f(x0)−f⋆\Delta = f(\vb{x}_0) - f^\star plus the TT noise increases.

The bound’s two terms play opposite roles. The first, 2Δ/(ηT)2\Delta/(\eta T), is deterministic gradient descent’s: it decays as 1/T1/T and prefers large steps. The second, ηLσ2\eta L\sigma^2, does not decay: a noise floor proportional to step size. With constant step, SGD does not bring the gradient to zero; it reaches a region sized by η\eta.

InteractiveThe Ghadimi–Lan bound in action
Large circle: start. Filled dots: endpoints of the 48 runs. Small circles: local minima.
  • measured: mean of (1/T) Σ ‖∇f(x_k)‖²
  • measured: instantaneous ‖∇f(x_T)‖²
  • bound 2Δ/(ηT) + ηLσ²
0.0501
1.50
LL and Δ=f(x0)−f⋆\Delta = f(\vb{x}_0) - f^\star4.2 and 6.13
Measured at T=2000T = 20000.289
Bound at T=2000T = 20000.596
Step minimizing the bound, η⋆\eta^\star0.0255
Runs in the global minimum basin0 %
The step nearly balances both terms in the bound. See where the paths end: a small gradient does not mean a global minimum.
SGD with noise variance σ2\sigma^2 on f(x,y)=φ(x)+φ(y)f(x, y) = \varphi(x) + \varphi(y), φ(u)=0.1u2+1−cos⁡2u\varphi(u) = 0.1u^2 + 1 - \cos 2u, a 4.24.2-smooth function with 49 local minima (35 inside the window) and f⋆=0f^\star = 0 at the origin. Top: 6 of 48 runs and all final points. Bottom: on log-log axes, mean 1T∑k<T∥∇f(xk)∥2\frac{1}{T}\sum_{k<T}\norm{\grad f(\vb{x}_k)}^2 against the bound. Increase step size: the bound drops sooner but plateaus higher. Select the bound's optimal step and compare with the measured curve. Then count runs ending at the global minimum.

The figure shows three things. The bound always holds and has the correct shape: decline as 1/T1/T and plateau proportional to η\eta. It is also fairly tight in this landscape (at T=2000T = 2000 the measured curve is within a factor of 1.3 to 3 of the bound, depending on step), because noise is exactly σ2\sigma^2 each step and curvature reaches LL near each well’s bottom; on real problems, where LL and σ2\sigma^2 are worst-case bounds, slack is greater, as the implementation shows. With defaults, none of the 48 runs reaches the global minimum: all stay in the nearest local minimum to the start. The theorem says nothing about that and cannot: under these assumptions finding the global minimum is generally NP-hard. Lesson 23 studies landscapes with the strict saddle property, where SGD’s stationary points are good.

The optimal step and the cost of a stationary point

For known horizon TT, the step minimizing the bound balances the two terms:

η⋆=min⁡{1L, 2ΔLσ2T}⟹1T∑k=0T−1E∥∇f(xk)∥2  ≤  2LΔT+2σ2LΔT.\eta^\star = \min\left\{\frac{1}{L},\ \sqrt{\frac{2\Delta}{L\sigma^2 T}}\right\} \quad\Longrightarrow\quad \frac{1}{T}\sum_{k=0}^{T-1}\E\norm{\grad f(\vb{x}_k)}^2 \;\le\; \frac{2L\Delta}{T} + 2\sigma\sqrt{\frac{2L\Delta}{T}} .

(If the minimum is 2Δ/(Lσ2T)\sqrt{2\Delta/(L\sigma^2 T)}, both terms equal σ2LΔ/T\sigma\sqrt{2L\Delta/T}; if it is 1/L1/L, then σ2≤2LΔ/T\sigma^2 \le 2L\Delta/T and the noise term is σ2≤σ2LΔ/T\sigma^2 \le \sigma\sqrt{2L\Delta/T}.) Two interpretations matter:

  • Which iterate to return. The bound concerns the average over TT iterates, not the last. Ghadimi and Lan return xR\vb{x}_R with RR uniformly randomly chosen in {0,…,T−1}\{0, \dots, T - 1\}: then E∥∇f(xR)∥2\E\norm{\grad f(\vb{x}_R)}^2 is exactly the mean on the left. In practice return the last or the best according to validation.
  • Cost. To guarantee E∥∇f(xR)∥≤ε\E\norm{\grad f(\vb{x}_R)} \le \eps it suffices for the right side to be at most ε2\eps^2, requiring T=O(LΔ/ε2+LΔσ2/ε4)T = \bigO\big(L\Delta/\eps^2 + L\Delta\sigma^2/\eps^4\big) oracle evaluations. Without noise we get gradient descent’s ε−2\eps^{-2}; with noise ε−4\eps^{-4} dominates. Arjevani, Carmon, Duchi, Foster, Srebro and Woodworth proved in 2019 that no stochastic first-order method improves ε−4\eps^{-4} with only these assumptions: SGD is optimal. If each stochastic gradient is also smooth in mean square, the lower bound falls to ε−3\eps^{-3}, attained by nonconvex variance-reduction methods such as SPIDER or STORM.

Decreasing steps

The same proof with a step ηk≤1/L\eta_k \le 1/L changing each iteration gives

∑k=0T−1ηk E∥∇f(xk)∥2  ≤  2Δ+Lσ2∑k=0T−1ηk2.\sum_{k=0}^{T-1}\eta_k\,\E\norm{\grad f(\vb{x}_k)}^2 \;\le\; 2\Delta + L\sigma^2\sum_{k=0}^{T-1}\eta_k^2 .

Dividing by ∑kηk\sum_k \eta_k, the weighted mean squared gradient tends to zero if ∑kηk=∞\sum_k\eta_k = \infty and ∑kηk2<∞\sum_k\eta_k^2 < \infty: Robbins–Monro conditions reappear in the nonconvex case. With ηk=c/k+1\eta_k = c/\sqrt{k + 1} (which almost, but does not, satisfy the second), ∑k<Tηk≈2cT\sum_{k<T}\eta_k \approx 2c\sqrt{T} and ∑k<Tηk2≈c2ln⁡T\sum_{k<T}\eta_k^2 \approx c^2\ln T, and the weighted mean is O(log⁡T/T)\bigO(\log T/\sqrt{T}): the same rate as optimal constant step up to a logarithm, without knowing TT. Enable decreasing step in the figure: the plateau vanishes.

Stochastic momentum

In lesson 9 heavy ball accelerated ill-conditioned problems. With noise, its first role is different: filtering. Unrolling the recurrence,

bk=∑j=0kβj gk−j,mk:=(1−β) bk=∑j=0k(1−β)βj gk−j.\vb{b}_k = \sum_{j=0}^{k}\beta^{j}\,\vb{g}_{k-j}, \qquad \vb{m}_k := (1 - \beta)\,\vb{b}_k = \sum_{j=0}^{k}(1 - \beta)\beta^{j}\,\vb{g}_{k-j}.

mk\vb{m}_k is an exponential moving average of gradients: weights (1−β)βj(1 - \beta)\beta^j summing to 1−βk+1→11 - \beta^{k+1} \to 1. PyTorch’s buffer is that average multiplied by 1/(1−β)1/(1 - \beta), and that gain yields three numbers characterizing momentum:

Proof

(1) is a geometric series. (2) By variance of a sum of independent terms, E∥∑j(1−β)βjξk−j∥2=∑j(1−β)2β2jσ2\E\norm{\sum_j(1 - \beta)\beta^j\vb{\xi}_{k-j}}^2 = \sum_j(1 - \beta)^2\beta^{2j}\sigma^2, and ∑j≥0β2j=1/(1−β2)\sum_{j \ge 0}\beta^{2j} = 1/(1 - \beta^2), so the limit is σ2(1−β)2/((1−β)(1+β))\sigma^2(1 - \beta)^2/((1 - \beta)(1 + \beta)). (3) Differentiating ∑jβj=1/(1−β)\sum_j\beta^j = 1/(1 - \beta) gives ∑jjβj−1=1/(1−β)2\sum_j j\beta^{j-1} = 1/(1 - \beta)^2; multiply by (1−β)β(1 - \beta)\beta.

∎

With β=0.9\beta = 0.9: gain 1010, window about 1010 steps, average noise reduced to 0.1/1.9≈0.23\sqrt{0.1/1.9} \approx 0.23 times and lag 99 steps. With β=0.99\beta = 0.99: gain 100100, noise 0.0710.071 times and lag 9999 steps.

InteractiveMomentum as a filter
  • stochastic gradient gkg_k
  • true gradient
  • exponential average mk=(1−β) bkm_k = (1 - \beta)\,b_k
Weights (1−β)βj(1 - \beta)\beta^j with which mkm_k mixes the gradient from jj steps ago
True gradient
View
0.900
1.00
Effective window 1/(1−β)1/(1 - \beta)10.0 steps
Mean lag β/(1−β)\beta/(1 - \beta)9.0 steps
Noise in mkm_k: measured and theoretical0.228 and 0.229
RMS error of mkm_k against ∇f\grad f0.334
Effective step η/(1−β)\eta/(1 - \beta)1.000
Press Best β to see which momentum minimizes error against the true gradient: it depends on how quickly the signal changes and how noisy it is.
Points: stochastic gradients gkg_k (true plus noise). Gray line: true gradient. Blue: exponential mean mkm_k. Increase β\beta to see noise fall but the curve lag behind the step. Select best β with different signals and noise levels: optimal inertia depends on how quickly the gradient changes. In displacement view, blue is movement per momentum step, η bk\eta\,b_k, and dashed is noise-free SGD movement with step η/(1−β)\eta/(1 - \beta): after roughly 1/(1−β)1/(1 - \beta) iterations they coincide. Below are filter weights.

With noise, momentum rescales the step

Point 2 suggests momentum reduces noise. But point 1 says it also multiplies the step by 1/(1−β)1/(1 - \beta), and a larger step amplifies iterate noise. What is gained? On a quadratic we can calculate exactly.

Proof

Write a=1+β−ηha = 1 + \beta - \eta h, so xk+1=axk−βxk−1−ηξkx_{k+1} = a x_k - \beta x_{k-1} - \eta\xi_k, and call γ0=E[xk2]\gamma_0 = \E[x_k^2] and γ1=E[xkxk−1]\gamma_1 = \E[x_k x_{k-1}] at stationarity. As ξk\xi_k is independent of xkx_k and xk−1x_{k-1}, multiplying the recurrence by xkx_k and taking expectations gives γ1=aγ0−βγ1\gamma_1 = a\gamma_0 - \beta\gamma_1, that is γ1=aγ0/(1+β)\gamma_1 = a\gamma_0/(1 + \beta). Squaring gives γ0=a2γ0+β2γ0−2aβγ1+η2σ2\gamma_0 = a^2\gamma_0 + \beta^2\gamma_0 - 2a\beta\gamma_1 + \eta^2\sigma^2. Substitute γ1\gamma_1,

γ0[(1−β2)−a2 1−β1+β]=η2σ2,(1−β2)−a2 1−β1+β=1−β1+β[(1+β)2−a2].\gamma_0\Big[(1 - \beta^2) - a^2\,\frac{1 - \beta}{1 + \beta}\Big] = \eta^2\sigma^2, \qquad (1 - \beta^2) - a^2\,\frac{1 - \beta}{1 + \beta} = \frac{1 - \beta}{1 + \beta}\big[(1 + \beta)^2 - a^2\big].

And (1+β)2−a2=ηh (2(1+β)−ηh)(1 + \beta)^2 - a^2 = \eta h\,\big(2(1 + \beta) - \eta h\big), yielding the formula. The case β=0\beta = 0 is SGD’s.

∎

Yuan, Ying and Sayed (2016) proved this generally for strongly convex problems: in the small-step regime where noise dominates, SGD with momentum (η,β)(\eta, \beta) and SGD with step η/(1−β)\eta/(1 - \beta) are equivalent to first order. Momentum does not buy free noise reduction; it buys a larger step and pays proportionately in noise. Its real advantage appears outside that regime: early, almost deterministic training, when lesson 9’s acceleration acts on low-curvature directions, and when equivalent step η/(1−β)\eta/(1 - \beta) approaches SGD’s 2/h2/h stability limit, which heavy ball tolerates much better (its limit is ηh<2(1+β)\eta h < 2(1 + \beta)). With η=0.1\eta = 0.1, β=0.9\beta = 0.9 and h=1h = 1, the equivalent step is 1, half that limit, and momentum gives E[x2]=0.51 σ2\E[x^2] = 0.51\,\sigma^2, while SGD with α=1\alpha = 1 gives 1.0 σ21.0\,\sigma^2. Kidambi and coauthors (2018) also showed that for linear regression with stochastic gradients neither heavy ball nor Nesterov generally improves on SGD.

The practical consequence is immediate. η\eta and β\beta are not independent hyperparameters: what stays comparable between configurations is η/(1−β)\eta/(1 - \beta). Going from β=0.9\beta = 0.9 to β=0.99\beta = 0.99 without dividing η\eta by 10 multiplies the effective step by 10.

Learning-rate schedules

Convex and nonconvex SGD theory justifies decaying the step, and inverse schedules translate it literally. But actually used shapes (cosine, stepwise, WSD) are not 1/k1/k: they maintain a large step through most training and lower it quickly at the end. The reason is the previous lesson’s noise ball, now quantified.

Quantifying the noise ball

Take quadratic f(x)=12∑ihixi2f(\vb{x}) = \frac{1}{2}\sum_i h_i x_i^2 in the Hessian eigenvector basis, with gradients gk,i=hixk,i+ξk,ig_{k,i} = h_i x_{k,i} + \xi_{k,i} and independent variance-σi2\sigma_i^2 noise in each coordinate. Each coordinate evolves separately: xk+1,i=(1−ηkhi)xk,i−ηkξk,ix_{k+1,i} = (1 - \eta_k h_i)x_{k,i} - \eta_k\xi_{k,i}. Squaring and taking expectations, second moment uk,i=E[xk,i2]u_{k,i} = \E[x_{k,i}^2] obeys an exact deterministic recurrence,

uk+1,i=(1−ηkhi)2 uk,i+ηk2σi2,u_{k+1,i} = (1 - \eta_k h_i)^2\,u_{k,i} + \eta_k^2\sigma_i^2 ,

which splits into two parts: bias, (1−ηkhi)2(1 - \eta_k h_i)^2 per step applied to x0,i2x_{0,i}^2, and variance, what noise adds. With constant step η<2/hi\eta < 2/h_i, variance converges to ησi2/(hi(2−ηhi))\eta\sigma_i^2/(h_i(2 - \eta h_i)), and expected loss to

Ef(x∞)−f⋆=∑iη σi22 (2−ηhi)  ≈  η4∑iσi2=η4tr⁡Σ(ηhi≪1),\E f(\vb{x}_\infty) - f^\star = \sum_i \frac{\eta\,\sigma_i^2}{2\,(2 - \eta h_i)} \;\approx\; \frac{\eta}{4}\sum_i\sigma_i^2 = \frac{\eta}{4}\tr\mat{\Sigma} \qquad (\eta h_i \ll 1),

where Σ\mat{\Sigma} is gradient-noise covariance.

Two facts explain nearly everything schedules do:

  1. The noise floor is proportional to step size and independent of curvature: dividing η\eta by 10 divides remaining noise loss by 10.
  2. Each direction equilibrates in roughly 1/(2ηhi)1/(2\eta h_i) steps. High-curvature directions do so immediately; low-curvature directions take a very long time, and their remainder is bias, not noise: initial distance not yet covered. Reducing this bias requires accumulating a large ∑kηkhi\sum_k\eta_k h_i, that is, large steps for a long time.

The conflict is set: bias wants large η\eta, variance small η\eta. All modern schedules solve it by separating phases in time: high η\eta while bias dominates, then a final drop lowering the noise floor. Because variance re-equilibrates in 1/(2ηhi)1/(2\eta h_i) steps in high-curvature directions, which accumulate the most noise when σi2\sigma_i^2 grows with hih_i (common in networks, where gradient covariance resembles the Hessian), loss responds to each reduction almost immediately. That is why stepwise training curves have steps, and why the last 10 or 20% of WSD training yields a sharp drop.

InteractiveLearning-rate schedule designer
  • single run
  • constant η
  • η_k noise floor
  • this schedule (mean of 6)
Shape
1.00
5 % of T
20 % of T
0 % of maximum
Final loss: Constant0.0822
Final loss: Steps0.03
Final loss: 1/t0.0896
Final loss: Cosine0.0291
Final loss: WSD0.0138
Noise floor at maximum η\eta0.0552
Initially stable step, 2/hmax⁡2/h_{\max}0.20
A long plateau at high η\eta reduces bias in low-curvature directions, followed by a short cooldown that lowers the noise floor: the sharp final drop.
SGD on a noisy 100-dimensional quadratic with curvatures hi=i−1.5h_i = i^{-1.5} (1 to 10−310^{-3}), noise variance 0.0625 hi0.0625\,h_i and quartic term 13hixi4/4\frac{1}{3}h_i x_i^4/4 making maximum initial curvature 10 times its final value. Above, schedule; below, mean loss over 6 runs (same noise for all schedules), one individual run, constant η\eta as reference, and the noise floor for each ηk\eta_k. Watch loss follow the floor as ηk\eta_k falls. Remove warmup with ηmax⁡=1\eta_{\max} = 1. Calculate cosine for 2T. Compare final losses for the five shapes.

Warmup

In the figure, without warmup, ηmax⁡=1\eta_{\max} = 1 diverges in the first steps; with 5% warmup it is stable and finishes with loss roughly three times lower than the best ηmax⁡\eta_{\max} stable without warmup (slightly below 0.50.5). Curvature is not constant. Initially the iterate is far from the minimum and maximum curvature is hmax⁡≈10h_{\max} \approx 10: a step larger than 2/hmax⁡=0.22/h_{\max} = 0.2 overshoots in the most curved direction, and if much larger the rebound lands in an even more curved region and the iterate escapes. As it approaches the minimum, curvature falls and the stable step rises to nearly 2. Warmup grows the step with the stability limit.

Something similar happens in real networks, though the mechanism is richer. Maximum Hessian curvature (sharpness) is often high initially and training self-regulates around 2/η2/\eta (lesson 24’s edge of stability). Goyal and coauthors (2017) trained ResNet-50 on ImageNet with batches of 8192, multiplying η\eta by batch growth (the linear scaling rule), and found training stable only with gradual five-epoch warmup. With Adam, warmup has a second role: initially the second-moment estimate uses very few gradients and per-coordinate steps may be enormous. See warmup in networks.

Cosine and WSD: the horizon matters

Cosine is a smooth shape spending most time with high η\eta and falling to ηmin⁡\eta_{\min} precisely at step TT. Its drawback is dependence on TT. If calculated for 2T2T and training stops at TT, it finishes half-cooled with a high noise floor. If calculated for T/2T/2, the second half is spent with a tiny step that no longer reduces bias. A completed run cannot be extended without reheating.

WSD (warmup, stable, decay) solves this: the stable phase does not depend on the horizon, and short decay can launch from any saved stable-phase checkpoint. Hägele and coauthors (2024) showed decay over 10–20% of steps (linear or the slightly better 1−x1 - \sqrt{x} shape) matches or improves cosine in language-model pretraining, making scaling-law studies much cheaper: one long run with several cooldowns gives points for several budgets. In the figure’s defaults, WSD finishes below cosine because it spends more time at ηmax⁡\eta_{\max} and removes more bias from slow directions.

[ ]Bias and variance under four schedules, exactlyBrowser
import numpy as np
import matplotlib.pyplot as plt

# Cuadrática ruidosa: f(x) = sum_i h_i x_i^2 / 2, gradiente h_i x_i + ruido de varianza s^2 h_i.
# Los segundos momentos de SGD evolucionan de forma exacta y determinista:
#   sesgo:    b <- (1 - eta h)^2 b                   (lo que queda de x_0)
#   varianza: v <- (1 - eta h)^2 v + eta^2 s^2 h     (lo que añade el ruido)
d, s, T = 1000, 0.3, 2000
h = np.arange(1, d + 1) ** -1.3
x0 = np.ones(d)

def esperanza(eta):
    b, v = x0**2, np.zeros(d)
    curva = np.empty((len(eta), 2))
    for k, e in enumerate(eta):
        c = (1 - e * h) ** 2
        b, v = c * b, c * v + e**2 * s**2 * h
        curva[k] = 0.5 * h @ b, 0.5 * h @ v
    return curva                            # columnas: sesgo, varianza

def programa(tipo, eta_max=1.0, cool=0.2):
    k = np.arange(T)
    if tipo == "constante": return np.full(T, eta_max)
    if tipo == "escalones": return eta_max * np.select([k < T // 2, k < 3 * T // 4], [1.0, 0.1], 0.01)
    if tipo == "coseno":    return eta_max * 0.5 * (1 + np.cos(np.pi * k / T))
    if tipo == "WSD":
        D = int(cool * T)
        return np.where(k < T - D, eta_max, eta_max * (T - k) / D)

fig, ax = plt.subplots(1, 2, figsize=(10, 3.6))
for tipo in ["constante", "escalones", "coseno", "WSD"]:
    eta = programa(tipo)
    c = esperanza(eta)
    sesgo, var = c[-1]
    print(f"{tipo:10s} pérdida final {sesgo + var:.4f} = sesgo {sesgo:.4f} + varianza {var:.4f}")
    ax[0].plot(eta, label=tipo); ax[1].semilogy(c.sum(1), label=tipo)
suelo = np.sum(1.0 * s**2 * h / (2 * (2 - 1.0 * h)))
print(f"suelo de ruido con eta = 1: {suelo:.4f}   aproximación eta tr(Sigma)/4: {s**2 * h.sum() / 4:.4f}")
ax[0].set_title("programa η_k"); ax[1].set_title("pérdida esperada (exacta)")
ax[1].set_xlabel("paso k"); ax[1].legend(); plt.tight_layout(); plt.show()

With constant η\eta bias is lowest of the four, but variance stays at the floor; cosine and stepwise extinguish variance at the cost of more bias because they spend less time at a large step; WSD combines low plateau bias with final cooldown removing over 80% of variance. (The approximation ηtr⁡Σ/4\eta\tr\mat{\Sigma}/4 underestimates the exact floor here because in the highest-curvature directions ηhi\eta h_i reaches 1.) The model is linear with no changing curvature, but this bias–variance decomposition underlies empirical results.

Variance reduction: SVRG and SAGA

Return to the classic learning problem: a finite sum

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

with each fif_i convex and LL-smooth and ff μ\mu-strongly convex, condition number κ=L/μ\kappa = L/\mu. Gradient descent converges linearly, but each step costs nn gradients: O(nκlog⁡(1/ε))\bigO(n\kappa\log(1/\eps)) total. SGD costs one gradient per step, but its estimator ∇fi(x)\grad f_i(\vb{x}) has nonzero variance at the optimum,

σ⋆2=1n∑i=1n∥∇fi(x⋆)∥2>0(salvo si todos los ∇fi(x⋆)=0),\sigma_\star^2 = \frac{1}{n}\sum_{i=1}^n\norm{\grad f_i(\vb{x}^\star)}^2 > 0 \quad\text{(salvo si todos los } \grad f_i(\vb{x}^\star) = \vb{0}\text{)},

so with constant step it remains in a noise ball and with decreasing step converges as O(1/k)\bigO(1/k). Can we have both: SGD’s step cost and linear convergence?

The tool is a control variate. If XX unbiasedly estimates what we want and YY correlates with XX with known mean EY\E Y, then X−Y+EYX - Y + \E Y remains unbiased with variance Var⁡X+Var⁡Y−2Cov⁡(X,Y)\Var X + \Var Y - 2\Cov(X, Y) (by covariance), much smaller than Var⁡X\Var X if XX and YY are highly correlated. For gradients, X=∇fi(x)X = \grad f_i(\vb{x}) and the natural correlated variable is the gradient of the same example at a nearby point.

The estimator is unbiased, because Ei[∇fi(x~)]=μ~\E_i[\grad f_i(\tilde{\vb{x}})] = \tilde{\vb{\mu}}, and its variance is bounded by the distance between xt\vb{x}_t and x~\tilde{\vb{x}}: if each ∇fi\grad f_i is LL-Lipschitz,

E∥vt−∇f(xt)∥2  ≤  L2∥xt−x~∥2  ≤  2L2(∥xt−x⋆∥2+∥x~−x⋆∥2).\E\norm{\vb{v}_t - \grad f(\vb{x}_t)}^2 \;\le\; L^2\norm{\vb{x}_t - \tilde{\vb{x}}}^2 \;\le\; 2L^2\big(\norm{\vb{x}_t - \vb{x}^\star}^2 + \norm{\tilde{\vb{x}} - \vb{x}^\star}^2\big).

You will prove it in an exercise. This is the method’s heart: as xt\vb{x}_t and x~\tilde{\vb{x}} approach x⋆\vb{x}^\star, estimator variance tends to zero, and a constant step no longer produces a noise ball. At xt=x~=x⋆\vb{x}_t = \tilde{\vb{x}} = \vb{x}^\star the estimator equals exactly ∇fi(x⋆)−∇fi(x⋆)+0=0\grad f_i(\vb{x}^\star) - \grad f_i(\vb{x}^\star) + \vb{0} = \vb{0} for every ii.

InteractiveVanishing variance
  • SGD
  • SVRG (circle: reference x~\tilde{\vb{x}})
  • ∇f(x)\grad f(\vb{x}), the cloud mean
SGD estimatorswindow ±3
SVRG estimatorswindow ±3
  • SGD
  • SVRG
  • SAGA
  • GD (step 1/L)
30.0 passes
0.70
1.00
Right-hand cloud
Horizontal axis
SGD estimator variance0.7
SVRG estimator variance9.5·10⁻⁸
Bound Lmax⁡2∥x−x~∥2L_{\max}^2\norm{\vb{x} - \tilde{\vb{x}}}^21.1·10⁻⁵
∥x−x⋆∥2\norm{\vb{x} - \vb{x}^\star}^2: SGD4.2·10⁻³
∥x−x⋆∥2\norm{\vb{x} - \vb{x}^\star}^2: SVRG2.1·10⁻⁸
Lmax⁡L_{\max}, μ\mu and κ=Lmax⁡/μ\kappa = L_{\max}/\mu12.4, 0.44 and 28
The SVRG estimator variance is 1·10⁻⁷ times that of SGD. The red cloud never shrinks: at x⋆\vb{x}^\star it remains 1n∑i∥∇fi(x⋆)∥2\frac{1}{n}\sum_i \norm{\grad f_i(\vb{x}^\star)}^2.
Regularized least squares in 2D, sum of n=40n = 40 terms. SGD (red), SVRG (blue) and SAGA (aqua) use the same step. Below left, the 40 possible SGD estimator values at its current iterate; right, those of SVRG (or SAGA). The arrow is their mean ∇f(x)\grad f(\vb{x}) and the dashed circle has radius equal to standard deviation. Both windows share a scale adjusted to contain both clouds. Play: SVRG's cloud is a point whenever x~\tilde{\vb{x}} refreshes and opens as the iterate moves from its reference; on approaching x⋆\vb{x}^\star, SGD's cloud retains its size and SVRG's shrinks to a point. In the graph SVRG and SAGA error falls in a straight line on a log scale. Switch the axis to iterations to see how misleading that count is.

Linear convergence

The precise version needs a lemma on finite sums of smooth convex functions.

Proof

The function ϕi(x)=fi(x)−fi(x⋆)−⟨∇fi(x⋆),x−x⋆⟩\phi_i(\vb{x}) = f_i(\vb{x}) - f_i(\vb{x}^\star) - \inner{\grad f_i(\vb{x}^\star)}{\vb{x} - \vb{x}^\star} is convex, LL-smooth, nonnegative and zero at its minimum x⋆\vb{x}^\star. For such a function a gradient step of length 1/L1/L decreases it by at least 12L∥∇ϕi∥2\frac{1}{2L}\norm{\grad\phi_i}^2 (descent lemma), and it cannot fall below zero: ∥∇ϕi(x)∥2≤2L ϕi(x)\norm{\grad\phi_i(\vb{x})}^2 \le 2L\,\phi_i(\vb{x}). Since ∇ϕi(x)=∇fi(x)−∇fi(x⋆)\grad\phi_i(\vb{x}) = \grad f_i(\vb{x}) - \grad f_i(\vb{x}^\star), averaging over ii and using 1n∑i∇fi(x⋆)=∇f(x⋆)=0\frac{1}{n}\sum_i\grad f_i(\vb{x}^\star) = \grad f(\vb{x}^\star) = \vb{0}, the average of ϕi\phi_i is f(x)−f(x⋆)f(\vb{x}) - f(\vb{x}^\star).

∎
Proof

Fix an epoch and condition on x~\tilde{\vb{x}}. Splitting vt=[∇fi(xt)−∇fi(x⋆)]−[∇fi(x~)−∇fi(x⋆)−∇f(x~)]\vb{v}_t = [\grad f_i(\vb{x}_t) - \grad f_i(\vb{x}^\star)] - [\grad f_i(\tilde{\vb{x}}) - \grad f_i(\vb{x}^\star) - \grad f(\tilde{\vb{x}})] and using ∥a+b∥2≤2∥a∥2+2∥b∥2\norm{\vb{a} + \vb{b}}^2 \le 2\norm{\vb{a}}^2 + 2\norm{\vb{b}}^2 and that a random vector’s variance does not exceed its second moment (the mean of ∇fi(x~)−∇fi(x⋆)\grad f_i(\tilde{\vb{x}}) - \grad f_i(\vb{x}^\star) is ∇f(x~)\grad f(\tilde{\vb{x}})), the lemma gives

E∥vt∥2≤4L(f(xt)−f⋆+f(x~)−f⋆).\E\norm{\vb{v}_t}^2 \le 4L\big(f(\vb{x}_t) - f^\star + f(\tilde{\vb{x}}) - f^\star\big).

Since Evt=∇f(xt)\E\vb{v}_t = \grad f(\vb{x}_t) and, by convexity, ⟨∇f(xt),xt−x⋆⟩≥f(xt)−f⋆\inner{\grad f(\vb{x}_t)}{\vb{x}_t - \vb{x}^\star} \ge f(\vb{x}_t) - f^\star,

E∥xt+1−x⋆∥2≤∥xt−x⋆∥2−2η(1−2Lη)(f(xt)−f⋆)+4Lη2(f(x~)−f⋆).\E\norm{\vb{x}_{t+1} - \vb{x}^\star}^2 \le \norm{\vb{x}_t - \vb{x}^\star}^2 - 2\eta(1 - 2L\eta)\big(f(\vb{x}_t) - f^\star\big) + 4L\eta^2\big(f(\tilde{\vb{x}}) - f^\star\big).

Summing from t=0t = 0 to m−1m - 1, with x0=x~\vb{x}_0 = \tilde{\vb{x}}, discarding E∥xm−x⋆∥2≥0\E\norm{\vb{x}_m - \vb{x}^\star}^2 \ge 0 and using ∑t=0m−1E[f(xt)−f⋆]=m E[f(x~s+1)−f⋆]\sum_{t=0}^{m-1}\E[f(\vb{x}_t) - f^\star] = m\,\E[f(\tilde{\vb{x}}_{s+1}) - f^\star] by the random choice of new reference point,

2η(1−2Lη) m E[f(x~s+1)−f⋆]≤∥x~−x⋆∥2+4Lmη2(f(x~)−f⋆).2\eta(1 - 2L\eta)\,m\,\E\big[f(\tilde{\vb{x}}_{s+1}) - f^\star\big] \le \norm{\tilde{\vb{x}} - \vb{x}^\star}^2 + 4Lm\eta^2\big(f(\tilde{\vb{x}}) - f^\star\big).

By strong convexity, ∥x~−x⋆∥2≤2μ(f(x~)−f⋆)\norm{\tilde{\vb{x}} - \vb{x}^\star}^2 \le \frac{2}{\mu}(f(\tilde{\vb{x}}) - f^\star). Divide by 2η(1−2Lη)m2\eta(1 - 2L\eta)m.

∎

Each epoch costs n+2mn + 2m gradient evaluations and reduces error by a constant factor, with m=O(κ)m = \bigO(\kappa). Reaching accuracy ε\eps takes O(log⁡(1/ε))\bigO(\log(1/\eps)) epochs: O((n+κ)log⁡(1/ε))\bigO\big((n + \kappa)\log(1/\eps)\big) evaluations, versus gradient descent’s O(nκlog⁡(1/ε))\bigO(n\kappa\log(1/\eps)). Gain is a factor nκ/(n+κ)n\kappa/(n + \kappa), between 12min⁡(n,κ)\frac{1}{2}\min(n, \kappa) and min⁡(n,κ)\min(n, \kappa): huge when both nn and κ\kappa are large. (Accelerated versions, such as Allen-Zhu’s Katyusha, reach O((n+nκ)log⁡(1/ε))\bigO((n + \sqrt{n\kappa})\log(1/\eps)).)

SAGA: memory instead of epochs

It is the same control variate, with a different reference point for each example: its most recent evaluation point. There are no epochs or periodic full gradients, and each step costs one evaluation. With η=1/(3L)\eta = 1/(3L) it converges linearly, E∥xk−x⋆∥2≤(1−min⁡{14n,μ3L})kC0\E\norm{\vb{x}_k - \vb{x}^\star}^2 \le \big(1 - \min\{\tfrac{1}{4n}, \tfrac{\mu}{3L}\}\big)^k C_0, and unlike predecessor SAG (Le Roux, Schmidt and Bach, 2012), its estimator is unbiased, allowing combination with a proximal operator for composite objectives (proximal gradient with ℓ1\ell_1 regularization, for example). Its price is memory: nn vectors of dimension dd. For linear models, ∇fi(x)=ℓ′(ai⊤x,yi) ai\grad f_i(\vb{x}) = \ell'(\vb{a}_i\T\vb{x}, y_i)\,\vb{a}_i, and storing scalar ℓ′\ell' suffices: O(n)\bigO(n) memory. This is scikit-learn’s saga solver.

Why variance reduction did not take over deep learning

SVRG and SAGA are reference methods for large regularized linear models and are rarely used in neural networks. Defazio and Bottou (2019) carefully studied vision networks (from LeNet to ResNet and DenseNet) and found technical and fundamental obstacles:

  • Terms are not fixed. With data augmentation, fif_i depends on a different random transformation whenever an example is visited, so ∇fi(x~)\grad f_i(\tilde{\vb{x}}) and ∇fi(xt)\grad f_i(\vb{x}_t) are computed on different images and cease to be correlated. Batch normalization makes one example’s gradient depend on other batch members and moving statistics changing between reference and iterate; dropout adds another random source. Remedies exist (fix each example’s transformation during an epoch, recompute statistics), but complicate the method.
  • The reference gets stale. Even with remedies, in large networks the iterate moves so far from x~\tilde{\vb{x}} during an epoch that correlation between ∇fi(xt)\grad f_i(\vb{x}_t) and ∇fi(x~)\grad f_i(\tilde{\vb{x}}) is lost, and measured SVRG variance was almost the same as SGD after the first epochs. The bound L2∥xt−x~∥2L^2\norm{\vb{x}_t - \tilde{\vb{x}}}^2 predicts this: it is small only if the iterate barely moves between references.
  • Cost. SVRG makes two backward passes per step plus a full gradient per epoch: 2–3 times SGD’s compute per step. SAGA needs n×dn \times d memory numbers, impossible with millions of parameters.
  • The goal is not the empirical optimum. Variance reduction shines when R^\hat R must be minimized to many digits. Deep learning trains for a few epochs, stops using validation and seeks generalization; overparameterized networks are often in the interpolation regime, where ∇fi(x⋆)≈0\grad f_i(\vb{x}^\star) \approx \vb{0} for all ii and SGD already converges linearly unaided.

Their practical conclusion was that SVRG improved test error on none of the large networks tried. The ideas survived: momentum also reduces variance, cheaply but with bias by averaging past gradients, and STORM (Cutkosky and Orabona, 2019) adds an SVRG-like correction ∇fik(xk)−∇fik(xk−1)\grad f_{i_k}(\vb{x}_k) - \grad f_{i_k}(\vb{x}_{k-1}) on the same example, correcting that bias without full gradients and attaining nonconvex ε−3\eps^{-3} up to logarithmic factors.

Implementation from scratch

First, measure the Ghadimi–Lan bound on a genuinely nonconvex problem: robust regression with Geman–McClure loss φ(r)=r2/(1+r2)\varphi(r) = r^2/(1 + r^2), nonconvex and nonnegative. Its derivatives satisfy ∣φ′′∣≤2\abs{\varphi''} \le 2 and ∣φ′∣≤33/8\abs{\varphi'} \le 3\sqrt{3}/8, so all constants in the bound can be bounded honestly: L≤2λmax⁡(X⊤X/n)L \le 2\lambda_{\max}(\mat{X}\T\mat{X}/n), σ2≤E∥∇fi∥2≤(33/8)2 E∥xi∥2\sigma^2 \le \E\norm{\grad f_i}^2 \le (3\sqrt 3/8)^2\,\E\norm{\vb{x}_i}^2 and f⋆≥0f^\star \ge 0.

[ ]Measuring the nonconvex boundBrowser
import numpy as np

rng = np.random.default_rng(0)
n, d = 200, 5
X = rng.standard_normal((n, d))
w_true = rng.standard_normal(d)
y = X @ w_true + 0.1 * rng.standard_normal(n)
y[:30] += 8 * rng.standard_normal(30)            # 15 % de valores atípicos

def f(W):                                        # W: (R, d), una fila por ejecución
    r = y - W @ X.T
    return np.mean(r**2 / (1 + r**2), axis=1)

def grad_full(W):
    r = y - W @ X.T
    return -(2 * r / (1 + r**2) ** 2) @ X / n

def grad_i(W, idx):                              # un ejemplo distinto en cada ejecución
    Xi = X[idx]
    r = y[idx] - np.sum(W * Xi, axis=1)
    return -(2 * r / (1 + r**2) ** 2)[:, None] * Xi

L = 2 * np.linalg.eigvalsh(X.T @ X / n).max()   # |phi''| <= 2
sigma2 = (3 * np.sqrt(3) / 8) ** 2 * np.mean(np.sum(X**2, axis=1))
w0 = np.zeros(d)
Delta = f(w0[None])[0]                           # f(w0) - f* <= f(w0), porque f >= 0
print(f"L <= {L:.3f}   sigma^2 <= {sigma2:.3f}   Delta <= {Delta:.3f}")

R, T = 20, 2000
for eta in [0.01, 0.03, 0.1, 1 / L]:
    W = np.tile(w0, (R, 1))
    acc = np.zeros(R)
    for k in range(T):
        acc += np.sum(grad_full(W) ** 2, axis=1)
        W = W - eta * grad_i(W, rng.integers(n, size=R))
    medido = acc.mean() / T
    cota = 2 * Delta / (eta * T) + eta * L * sigma2
    print(f"eta = {eta:.3f}:  media de E||grad f||^2 = {medido:.2e}   cota = {cota:.2e}   (cota / medido = {cota / medido:.0f})")
print(f"paso que minimiza la cota para T = {T}: {np.sqrt(2 * Delta / (L * T * sigma2)):.4f}")

The bound holds in every case, with slack between 5 and 20, and reproduces the shape: at the largest step 1/L1/L, ηLσ2\eta L\sigma^2 dominates and mean gradient is worst of the four. The bound-minimizing step 0.0110.011 does not match the measured best 0.030.03: the bound uses worst possible variance and curvature, and the actual problem is more benign. This is the right use of bounds: they provide dependence shape and order of magnitude, not the hyperparameter.

Now momentum: buffer gain, exponential-average noise and theorem’s stationary variance, compared with SGD at step η/(1−β)\eta/(1 - \beta).

[ ]Momentum: gain, noise and equivalence to a larger stepBrowser
import numpy as np

rng = np.random.default_rng(1)

beta, g = 0.9, 1.0
b = g                                            # PyTorch: b_0 = g_0
for k in range(1, 200):
    b = beta * b + g
print(f"buffer con gradiente constante: {b:.6f}   1/(1 - beta) = {1 / (1 - beta):.6f}")

for beta in [0.5, 0.9, 0.99]:                    # ruido de la media exponencial
    m, acc, cnt = np.zeros(500), 0.0, 0
    for k in range(3000):
        m = beta * m + (1 - beta) * rng.standard_normal(500)
        if k >= 1000:
            acc += np.mean(m**2); cnt += 1
    print(f"beta = {beta}:  Var(m) = {acc / cnt:.5f}   (1 - beta)/(1 + beta) = {(1 - beta) / (1 + beta):.5f}")

def var_momentum(eta, beta, h=1.0, s=1.0):
    return eta * s**2 * (1 + beta) / (h * (1 - beta) * (2 * (1 + beta) - eta * h))

def var_sgd(alpha, h=1.0, s=1.0):
    return alpha * s**2 / (h * (2 - alpha * h))

R, T = 2000, 3000
for eta, beta in [(0.01, 0.9), (0.002, 0.99), (0.1, 0.9)]:
    x = np.zeros(R); xp = np.zeros(R); acc = 0.0
    for k in range(T):
        xn = x - eta * (x + rng.standard_normal(R)) + beta * (x - xp)
        xp, x = x, xn
        if k >= T // 2:
            acc += np.mean(x**2) / (T - T // 2)
    a = eta / (1 - beta)
    print(f"eta = {eta}, beta = {beta}:  E[x^2] medida {acc:.4f}   fórmula {var_momentum(eta, beta):.4f}"
          f"   SGD con paso {a:.2f}: {var_sgd(a):.4f}")

With small steps, momentum variance and SGD variance at step η/(1−β)\eta/(1 - \beta) differ by 5 or 10%; with η=0.1\eta = 0.1 and β=0.9\beta = 0.9, whose equivalent step 1 is halfway to SGD’s stability limit 2, momentum has half the variance. Exactly as the theorem predicts: equivalence holds to first order in step size and breaks when ηh/(1−β)\eta h/(1 - \beta) is no longer small.

Finally, SVRG and SAGA for logistic regression with ℓ2\ell_2 regularization, compared with gradient descent and SGD per data pass, counting all gradient evaluations. SAGA exploits that for a linear model ∇fi(w)=ci ai+λw\grad f_i(\vb{w}) = c_i\,\vb{a}_i + \lambda\vb{w} and only scalar cic_i need be stored.

[ ]SVRG and SAGA from scratchBrowser
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(0)
n, d, lam = 300, 10, 5e-2
A = rng.standard_normal((n, d)) * np.linspace(1.5, 0.3, d)
w_true = rng.standard_normal(d)
y = np.where(A @ w_true + 0.5 * rng.standard_normal(n) > 0, 1.0, -1.0)

def f(w):
    return np.mean(np.logaddexp(0, -y * (A @ w))) + lam / 2 * w @ w

def grad(w):
    c = -y / (1 + np.exp(y * (A @ w)))
    return A.T @ c / n + lam * w

def coef(w, i):                                    # grad f_i(w) = coef(w, i) a_i + lam w
    return -y[i] / (1 + np.exp(y[i] * (A[i] @ w)))

w = np.zeros(d)                                    # óptimo de referencia con Newton
for _ in range(30):
    p = 1 / (1 + np.exp(-y * (A @ w)))
    H = (A * (p * (1 - p))[:, None]).T @ A / n + lam * np.eye(d)
    w = w - np.linalg.solve(H, grad(w))
w_star, f_star = w, f(w)
L = 0.25 * np.max(np.sum(A**2, axis=1)) + lam      # cada f_i es L-suave
print(f"f* = {f_star:.6f}   L_max = {L:.2f}   kappa = L/lam = {L / lam:.0f}")
pasadas = 20

def gd(eta):
    w = np.zeros(d); hist = [(0, f(w) - f_star)]
    for k in range(pasadas):
        w = w - eta * grad(w); hist.append((k + 1, f(w) - f_star))
    return hist

def sgd(eta, seed=0):
    r = np.random.default_rng(seed); w = np.zeros(d); hist = [(0, f(w) - f_star)]
    for ep in range(pasadas):
        for i in r.integers(n, size=n):
            w = w - eta * (coef(w, i) * A[i] + lam * w)
        hist.append((ep + 1, f(w) - f_star))
    return hist

def svrg(eta, m, seed=0):
    r = np.random.default_rng(seed); w = np.zeros(d); evals = 0; hist = [(0, f(w) - f_star)]
    while evals < pasadas * n:
        w_ref = w.copy(); mu = grad(w_ref); evals += n             # gradiente completo: n evaluaciones
        for i in r.integers(n, size=m):
            v = (coef(w, i) - coef(w_ref, i)) * A[i] + lam * (w - w_ref) + mu
            w = w - eta * v
        evals += 2 * m                                             # dos evaluaciones por paso
        hist.append((evals / n, f(w) - f_star))
    return hist

def saga(eta, seed=0):
    r = np.random.default_rng(seed); w = np.zeros(d)
    tabla = np.array([coef(w, i) for i in range(n)])               # un escalar por ejemplo
    media = A.T @ tabla / n
    hist = [(1, f(w) - f_star)]                                    # la tabla inicial cuesta una pasada
    for ep in range(1, pasadas):
        for j in r.integers(n, size=n):
            c = coef(w, j)
            w = w - eta * ((c - tabla[j]) * A[j] + media + lam * w)
            media += (c - tabla[j]) * A[j] / n
            tabla[j] = c
        hist.append((ep + 1, f(w) - f_star))
    return hist

L_f = 0.25 * np.linalg.eigvalsh(A.T @ A / n).max() + lam
res = {"GD (1/L_f)": gd(1 / L_f), "SGD": sgd(0.5 / L), "SVRG (m = n)": svrg(0.5 / L, n), "SAGA": saga(1 / (3 * L))}
for nombre, h in res.items():
    h = np.array(h)
    print(f"{nombre:13s} tras ~10 pasadas: {h[np.argmin(np.abs(h[:, 0] - 10)), 1]:.1e}   tras 19-20: {h[-1, 1]:.1e}")
    plt.semilogy(h[:, 0], h[:, 1], "o-", ms=3, label=nombre)
for nombre in ("SVRG (m = n)", "SAGA"):
    h = np.array(res[nombre])
    pend = np.polyfit(h[1:, 0], np.log10(h[1:, 1]), 1)[0]
    print(f"{nombre}: el error se divide por {10**-pend:.1f} en cada pasada")
plt.xlabel("pasadas por los datos (gradientes evaluados / n)"); plt.ylabel("f(w) - f*"); plt.legend(); plt.show()

SGD stalls near 10−210^{-2}, its constant-step noise ball. Gradient descent converges linearly but slowly because each step costs a full pass. SVRG and SAGA drop in straight lines on a logarithmic scale, dividing error by 3 per pass and falling below 10−1010^{-10} in 20 passes. SAGA leads slightly here because each step costs one evaluation, not two.

The professional version

For linear models scikit-learn’s saga solver implements exactly the above algorithm (with a scalar table). Its objective is C∑iℓi(w)+12∥w∥2C\sum_i \ell_i(\vb{w}) + \frac{1}{2}\norm{\vb{w}}^2, ours multiplied by nCnC if C=1/(nλ)C = 1/(n\lambda).

[ ]scikit-learn saga versus our optimumBrowser
import numpy as np
from sklearn.linear_model import LogisticRegression

clf = LogisticRegression(solver="saga", C=1 / (n * lam), fit_intercept=False, tol=1e-12, max_iter=2000)
clf.fit(A, y)
w_sk = clf.coef_.ravel()
print(f"iteraciones (pasadas) de saga: {clf.n_iter_[0]}")
print(f"||w_sk - w*|| = {np.linalg.norm(w_sk - w_star):.1e}   f(w_sk) - f* = {f(w_sk) - f_star:.1e}")

In PyTorch, learning-rate schedules live in torch.optim.lr_scheduler (their API appeared in the scheduler API). The most flexible is LambdaLR, multiplying base rate by a function of step; standard shapes include StepLR and MultiStepLR (steps), CosineAnnealingLR, LinearLR (useful for warmup and WSD decay), OneCycleLR and SequentialLR, chaining several. Remember to call sched.step() once per optimizer step if the schedule is step-based (not per epoch), and after opt.step().

The following experiment compares four schedules with a fixed step budget, following any serious comparison protocol (specified in lesson 27 on rigorous optimizer benchmarking): the same model, maximum rate and batch order for all schedules, several seeds, and both training and separate test-set metrics (data split protocols). It is a small MLP on synthetic data with 10% random labels, running on CPU in under half a minute; for Fashion-MNIST simply change data, move them and the model to GPU, and set device = "cuda".

[ ]Four fixed-budget schedules on a small networkLocal GPU
import math, time
import torch
from torch import nn

torch.set_num_threads(2)
device = "cpu"                     # el modelo es diminuto: en CPU va más rápido que lanzar kernels en la GPU
t0 = time.time()

def datos(n, semilla):
    """Un MLP 'profesor' fijo etiqueta puntos de R^20 en 10 clases; 10 % de etiquetas al azar."""
    g = torch.Generator().manual_seed(semilla)
    W1 = torch.randn(20, 64, generator=torch.Generator().manual_seed(1)) / 20**0.5
    W2 = torch.randn(64, 10, generator=torch.Generator().manual_seed(2)) / 8
    X = torch.randn(n, 20, generator=g)
    y = (torch.tanh(X @ W1) @ W2).argmax(1)
    ruido = torch.rand(n, generator=g) < 0.1
    y[ruido] = torch.randint(0, 10, (int(ruido.sum()),), generator=g)
    return X, y

Xtr, ytr = datos(8192, 0)
Xte, yte = datos(4096, 1)
PASOS, LOTE, ETA, BETA = 1200, 64, 0.1, 0.9
WARM = int(0.05 * PASOS)

def factor(nombre):
    """Multiplicador de la tasa base en el paso k, para LambdaLR."""
    def f(k):
        w = min(1.0, (k + 1) / WARM)                         # warmup lineal, en todos menos 'constante'
        if nombre == "constante": return 1.0
        if nombre == "escalones": return w * (1.0 if k < PASOS // 2 else 0.1 if k < 3 * PASOS // 4 else 0.01)
        if nombre == "coseno":    return w * 0.5 * (1 + math.cos(math.pi * min(1.0, max(0, k - WARM) / (PASOS - WARM))))
        if nombre == "WSD":
            D = int(0.2 * PASOS)
            return w * (1.0 if k < PASOS - D else (PASOS - k) / D)
    return f

def entrenar(nombre, semilla):
    torch.manual_seed(semilla)
    modelo = nn.Sequential(nn.Linear(20, 128), nn.ReLU(), nn.Linear(128, 128), nn.ReLU(), nn.Linear(128, 10)).to(device)
    opt = torch.optim.SGD(modelo.parameters(), lr=ETA, momentum=BETA)
    sched = torch.optim.lr_scheduler.LambdaLR(opt, factor(nombre))
    perdida = nn.CrossEntropyLoss()
    gen = torch.Generator().manual_seed(100 + semilla)      # mismo orden de lotes para todos los programas
    for k in range(PASOS):
        idx = torch.randint(0, len(Xtr), (LOTE,), generator=gen)
        loss = perdida(modelo(Xtr[idx]), ytr[idx])
        opt.zero_grad(); loss.backward(); opt.step(); sched.step()
    with torch.no_grad():
        tr = perdida(modelo(Xtr), ytr).item()
        acc = (modelo(Xte).argmax(1) == yte).float().mean().item()
    modelo.zero_grad(); perdida(modelo(Xtr), ytr).backward()   # norma del gradiente completo al final
    gn = math.sqrt(sum((p.grad**2).sum().item() for p in modelo.parameters()))
    return tr, acc, gn

for nombre in ["constante", "escalones", "coseno", "WSD"]:
    res = torch.tensor([entrenar(nombre, s) for s in (0, 1, 2)])
    m, s = res.mean(0), res.std(0)
    print(f"{nombre:10s} pérdida de entrenamiento {m[0]:.4f} ± {s[0]:.4f}   acierto en test {m[1]:.4f} ± {s[1]:.4f}"
          f"   ||grad f|| final {m[2]:.3f}")
print(f"tiempo: {time.time() - t0:.1f} s")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Across three seeds, results are clear and somewhat uncomfortable. Constant scheduling is worst in test (67.6 %67.6\,\%) and final full-gradient norm, 0.250.25 (the high-η\eta noise floor), versus 0.060.06 to 0.110.11 for the others; it ties stepwise in training loss. WSD gets the lowest training loss (0.590.59 versus 0.650.65 cosine and 0.710.71 stepwise), as bias–variance analysis predicts. But cosine and stepwise win in test accuracy (72.1 %72.1\,\% versus WSD’s 70.2 %70.2\,\%), with differences larger than seed-to-seed variation: with 10% random labels, better training optimization also means fitting noise better. The schedule optimizing best need not generalize best, and an honest comparison fixes the deciding metric in advance, tunes ηmax⁡\eta_{\max} separately per schedule and records all runs (as in experiment tracking).

Common mistakes

Exercises

ProofThe nonconvex SGD bound
Prove: If ff is LL-smooth with f⋆=inf⁡f>−∞f^\star = \inf f > -\infty, the oracle is unbiased with variance bounded by σ2\sigma^2, and 0<η≤1/L0 < \eta \le 1/L, then SGD satisfies 1T∑k=0T−1E∥∇f(xk)∥2≤2(f(x0)−f⋆)ηT+ηLσ2\frac{1}{T}\sum_{k=0}^{T-1}\E\norm{\grad f(\vb{x}_k)}^2 \le \frac{2(f(\vb{x}_0) - f^\star)}{\eta T} + \eta L\sigma^2.
0
Write xk+1=xk−ηgk\vb{x}_{k+1} = \vb{x}_k - \eta\vb{g}_k and abbreviate ∇fk=∇f(xk)\grad f_k = \grad f(\vb{x}_k).

Step 1 of 4. Which inequality compares f(xk+1)f(\vb{x}_{k+1}) with f(xk)f(\vb{x}_k)?

NumericBest step for a horizon
A 1010-smooth function has f(x0)−f⋆=2f(\vb{x}_0) - f^\star = 2 and oracle variance σ2=4\sigma^2 = 4. With T=104T = 10^4 SGD steps, what is the minimum over η∈(0,1/L]\eta \in (0, 1/L] of the bound 2ΔηT+ηLσ2\frac{2\Delta}{\eta T} + \eta L\sigma^2?
NumericMomentum's effective step
With torch.optim.SGD(lr=0.1, momentum=0.9) (without dampening), what is the steady-state effective step, i.e. the step of SGD without momentum producing the same mean displacement when the gradient is approximately constant?
NumericHow much noise passes the filter?
Stochastic gradients of one coordinate have independent noise with standard deviation σ=1\sigma = 1. What is the stationary standard deviation of noise in exponential mean mk=βmk−1+(1−β)gkm_k = \beta m_{k-1} + (1 - \beta) g_k with β=0.9\beta = 0.9?
QuizWhat does momentum buy with noise?
SGD with momentum (η,β)(\eta, \beta) on a quadratic with noisy gradients, with ηh\eta h small relative to 1−β1 - \beta. Which statement about iterate stationary variance is correct?
NumericReading cosine schedule with warmup
A pretraining run uses ηmax⁡=3×10−4\eta_{\max} = 3\times 10^{-4}, linear warmup of W=1000W = 1000 steps then cosine down to ηmin⁡=0\eta_{\min} = 0 at T=10000T = 10000: ηk=12ηmax⁡(1+cos⁡π(k−W)T−W)\eta_k = \frac{1}{2}\eta_{\max}\big(1 + \cos\frac{\pi(k - W)}{T - W}\big). What is ηk\eta_k at step k=7750k = 7750?
QuizExtending training
You pretrained a model for 50000 steps with cosine calculated for T=50000T = 50000 and now have budget for 25000 more. What is most reasonable given this lesson?
NumericSVRG's contraction factor
With η=1/(8L)\eta = 1/(8L) and m=40κm = 40\kappa inner steps (κ=L/μ\kappa = L/\mu), what is factor α=1μη(1−2Lη)m+2Lη1−2Lη\alpha = \frac{1}{\mu\eta(1 - 2L\eta)m} + \frac{2L\eta}{1 - 2L\eta} in Johnson and Zhang's theorem?
ProofSVRG estimator: unbiased with vanishing variance
Prove: Let f=1n∑ifif = \frac{1}{n}\sum_i f_i with each ∇fi\grad f_i LL-Lipschitz, ii uniform in {1,…,n}\{1, \dots, n\} and v=∇fi(x)−∇fi(x~)+∇f(x~)\vb{v} = \grad f_i(\vb{x}) - \grad f_i(\tilde{\vb{x}}) + \grad f(\tilde{\vb{x}}). Then Eiv=∇f(x)\E_i\vb{v} = \grad f(\vb{x}) and Ei∥v−∇f(x)∥2≤2L2(∥x−x⋆∥2+∥x~−x⋆∥2)\E_i\norm{\vb{v} - \grad f(\vb{x})}^2 \le 2L^2\big(\norm{\vb{x} - \vb{x}^\star}^2 + \norm{\tilde{\vb{x}} - \vb{x}^\star}^2\big).
0
Fix x\vb{x} and x~\tilde{\vb{x}}; the only randomness is index ii.

Step 1 of 4. Why is it unbiased?

CodeSVRG from scratch
Implement svrg(grad_i, full_grad, n, x0, eta, m, epochs, seed=0). At each of the epochs epochs, take current iterate as reference x~\tilde{\vb{x}}, save it in list refs, compute μ~\tilde{\vb{\mu}} = full_grad(x_ref) and take m steps with i = rng.integers(n) and v=∇fi(x)−∇fi(x~)+μ~\vb{v} = \grad f_i(\vb{x}) - \grad f_i(\tilde{\vb{x}}) + \tilde{\vb{\mu}}, x←x−ηv\vb{x} \leftarrow \vb{x} - \eta\vb{v}, where rng = np.random.default_rng(seed). Return (x, refs): the last iterate and reference points list (first is x0). Tests check linear convergence and that estimator variance, calculated exactly over nn indices, tends to zero.
import numpy as np

def svrg(grad_i, full_grad, n, x0, eta, m, epochs, seed=0):
  rng = np.random.default_rng(seed)
  x = np.array(x0, dtype=float)
  refs = []
  for s in range(epochs):
      refs.append(x.copy())
      # ahora mismo esto es SGD: falta la variable de control
      for _ in range(m):
          i = rng.integers(n)
          x = x - eta * grad_i(x, i)
  return x, refs
Shift+Enter to run
QuizSVRG on a ResNet
You train a ResNet on CIFAR-10 with data augmentation and batch normalization and carefully implement SVRG. After the first epochs its measured estimator variance is almost equal to SGD's. What is the main explanation?

Summary

Key idea
With noise, step size decides where SGD ends: the noise floor is proportional to η\eta. Momentum scales it by 1/(1−β)1/(1 - \beta), schedules lower it only after bias has been spent, and variance reduction removes it in finite sums by making estimator noise vanish at the optimum.
  • On an LL-smooth nonconvex function, SGD with η≤1/L\eta \le 1/L satisfies 1T∑kE∥∇f(xk)∥2≤2ΔηT+ηLσ2\frac{1}{T}\sum_k\E\norm{\grad f(\vb{x}_k)}^2 \le \frac{2\Delta}{\eta T} + \eta L\sigma^2. With optimal step, finding an ε\eps-stationary point costs O(ε−4)\bigO(\eps^{-4}) gradients, which no stochastic first-order method improves under these assumptions. The bound says nothing about which stationary point is reached.
  • PyTorch’s momentum buffer is 1/(1−β)1/(1 - \beta) times an exponential gradient average: effective step η/(1−β)\eta/(1 - \beta), noise reduced to (1−β)/(1+β)\sqrt{(1 - \beta)/(1 + \beta)} and lag β/(1−β)\beta/(1 - \beta) steps. With dominant noise it is equivalent to SGD with step η/(1−β)\eta/(1 - \beta).
  • Stationary SGD loss is approximately η4tr⁡Σ\frac{\eta}{4}\tr\mat{\Sigma}, and each direction equilibrates in roughly 1/(2ηhi)1/(2\eta h_i) steps. Thus high η\eta reduces bias, final decay reduces variance almost immediately, and loss falls in steps.
  • Warmup follows the stability limit 2/hmax⁡2/h_{\max}, lower initially. Cosine depends on the horizon; WSD does not, and its short cooldown matches or improves cosine.
  • SVRG and SAGA use the same example’s gradient at a reference point as a control variate: the estimator remains unbiased and variance vanishes at optimum. They converge linearly at cost O((n+κ)log⁡(1/ε))\bigO((n + \kappa)\log(1/\eps)), counted in evaluated gradients, not iterations.
  • Variance reduction barely helps in deep learning: data augmentation, batch normalization and fast iterate movement destroy the required correlation, and extra cost is not recovered.