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
- 06Stochastic gradient descentSGD convergence for convex problemsMinibatch gradient variance and gradient noise scaleHeavy-ball momentumGradient descent convergence to stationary pointsIterate averagingRobbins-Monro stochastic approximation
- 04Variance of sumsCovariance
- 00Canonical training and evaluation loopMap-style and iterable datasetsExperiment metric tracking
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 , or 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 : it rises for thousands of steps, stays high and finally plunges. There is inertia nobody justifies. And variance-reduction methods, which turn SGD’s 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 , 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 : when noise dominates, SGD with momentum behaves like SGD with step .
- 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 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 is an -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 in expectation by at least and increases it by at most due to noise. Summing steps, total decrease cannot exceed budget plus the noise increases.
The bound’s two terms play opposite roles. The first, , is deterministic gradient descent’s: it decays as and prefers large steps. The second, , 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 .
The figure shows three things. The bound always holds and has the correct shape: decline as and plateau proportional to . It is also fairly tight in this landscape (at the measured curve is within a factor of 1.3 to 3 of the bound, depending on step), because noise is exactly each step and curvature reaches near each well’s bottom; on real problems, where and 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 , the step minimizing the bound balances the two terms:
(If the minimum is , both terms equal ; if it is , then and the noise term is .) Two interpretations matter:
- Which iterate to return. The bound concerns the average over iterates, not the last. Ghadimi and Lan return with uniformly randomly chosen in : then is exactly the mean on the left. In practice return the last or the best according to validation.
- Cost. To guarantee it suffices for the right side to be at most , requiring oracle evaluations. Without noise we get gradient descent’s ; with noise dominates. Arjevani, Carmon, Duchi, Foster, Srebro and Woodworth proved in 2019 that no stochastic first-order method improves with only these assumptions: SGD is optimal. If each stochastic gradient is also smooth in mean square, the lower bound falls to , attained by nonconvex variance-reduction methods such as SPIDER or STORM.
Decreasing steps
The same proof with a step changing each iteration gives
Dividing by , the weighted mean squared gradient tends to zero if and : Robbins–Monro conditions reappear in the nonconvex case. With (which almost, but does not, satisfy the second), and , and the weighted mean is : the same rate as optimal constant step up to a logarithm, without knowing . 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,
is an exponential moving average of gradients: weights summing to . PyTorch’s buffer is that average multiplied by , and that gain yields three numbers characterizing momentum:
Proof
(1) is a geometric series. (2) By variance of a sum of independent terms, , and , so the limit is . (3) Differentiating gives ; multiply by .
∎With : gain , window about steps, average noise reduced to times and lag steps. With : gain , noise times and lag steps.
With noise, momentum rescales the step
Point 2 suggests momentum reduces noise. But point 1 says it also multiplies the step by , and a larger step amplifies iterate noise. What is gained? On a quadratic we can calculate exactly.
Proof
Write , so , and call and at stationarity. As is independent of and , multiplying the recurrence by and taking expectations gives , that is . Squaring gives . Substitute ,
And , yielding the formula. The case 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 and SGD with step 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 approaches SGD’s stability limit, which heavy ball tolerates much better (its limit is ). With , and , the equivalent step is 1, half that limit, and momentum gives , while SGD with gives . 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. and are not independent hyperparameters: what stays comparable between configurations is . Going from to without dividing 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 : 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 in the Hessian eigenvector basis, with gradients and independent variance- noise in each coordinate. Each coordinate evolves separately: . Squaring and taking expectations, second moment obeys an exact deterministic recurrence,
which splits into two parts: bias, per step applied to , and variance, what noise adds. With constant step , variance converges to , and expected loss to
where is gradient-noise covariance.
Two facts explain nearly everything schedules do:
- The noise floor is proportional to step size and independent of curvature: dividing by 10 divides remaining noise loss by 10.
- Each direction equilibrates in roughly 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 , that is, large steps for a long time.
The conflict is set: bias wants large , variance small . All modern schedules solve it by separating phases in time: high while bias dominates, then a final drop lowering the noise floor. Because variance re-equilibrates in steps in high-curvature directions, which accumulate the most noise when grows with (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.
Warmup
In the figure, without warmup, diverges in the first steps; with 5% warmup it is stable and finishes with loss roughly three times lower than the best stable without warmup (slightly below ). Curvature is not constant. Initially the iterate is far from the minimum and maximum curvature is : a step larger than 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 (lesson 24’s edge of stability). Goyal and coauthors (2017) trained ResNet-50 on ImageNet with batches of 8192, multiplying 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 and falling to precisely at step . Its drawback is dependence on . If calculated for and training stops at , it finishes half-cooled with a high noise floor. If calculated for , 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 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 and removes more bias from slow directions.
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 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 underestimates the exact floor here because in the highest-curvature directions 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
with each convex and -smooth and -strongly convex, condition number . Gradient descent converges linearly, but each step costs gradients: total. SGD costs one gradient per step, but its estimator has nonzero variance at the optimum,
so with constant step it remains in a noise ball and with decreasing step converges as . Can we have both: SGD’s step cost and linear convergence?
The tool is a control variate. If unbiasedly estimates what we want and correlates with with known mean , then remains unbiased with variance (by covariance), much smaller than if and are highly correlated. For gradients, and the natural correlated variable is the gradient of the same example at a nearby point.
The estimator is unbiased, because , and its variance is bounded by the distance between and : if each is -Lipschitz,
You will prove it in an exercise. This is the method’s heart: as and approach , estimator variance tends to zero, and a constant step no longer produces a noise ball. At the estimator equals exactly for every .
Linear convergence
The precise version needs a lemma on finite sums of smooth convex functions.
Proof
The function is convex, -smooth, nonnegative and zero at its minimum . For such a function a gradient step of length decreases it by at least (descent lemma), and it cannot fall below zero: . Since , averaging over and using , the average of is .
∎Proof
Fix an epoch and condition on . Splitting and using and that a random vector’s variance does not exceed its second moment (the mean of is ), the lemma gives
Since and, by convexity, ,
Summing from to , with , discarding and using by the random choice of new reference point,
By strong convexity, . Divide by .
∎Each epoch costs gradient evaluations and reduces error by a constant factor, with . Reaching accuracy takes epochs: evaluations, versus gradient descent’s . Gain is a factor , between and : huge when both and are large. (Accelerated versions, such as Allen-Zhu’s Katyusha, reach .)
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 it converges linearly, , 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 regularization, for example). Its price is memory: vectors of dimension . For linear models, , and storing scalar suffices: 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, depends on a different random transformation whenever an example is visited, so and 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 during an epoch that correlation between and is lost, and measured SVRG variance was almost the same as SGD after the first epochs. The bound 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 memory numbers, impossible with millions of parameters.
- The goal is not the empirical optimum. Variance reduction shines when 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 for all 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 on the same example, correcting that bias without full gradients and attaining nonconvex up to logarithmic factors.
Implementation from scratch
First, measure the Ghadimi–Lan bound on a genuinely nonconvex problem: robust regression with Geman–McClure loss , nonconvex and nonnegative. Its derivatives satisfy and , so all constants in the bound can be bounded honestly: , and .
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 , dominates and mean gradient is worst of the four. The bound-minimizing step does not match the measured best : 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 .
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 differ by 5 or 10%; with and , 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 is no longer small.
Finally, SVRG and SAGA for logistic regression with regularization, compared with gradient descent and SGD per data pass, counting all gradient evaluations. SAGA exploits that for a linear model and only scalar need be stored.
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 , 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 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 , ours multiplied by if .
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".
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")npm run lab and open the connection link.Across three seeds, results are clear and somewhat uncomfortable. Constant scheduling is worst in test () and final full-gradient norm, (the high- noise floor), versus to for the others; it ties stepwise in training loss. WSD gets the lowest training loss ( versus cosine and stepwise), as bias–variance analysis predicts. But cosine and stepwise win in test accuracy ( versus WSD’s ), 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 separately per schedule and records all runs (as in experiment tracking).
Common mistakes
Exercises
Step 1 of 4. Which inequality compares 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?Step 1 of 4. Why is it unbiased?
svrg(grad_i, full_grad, n, x0, eta, m, epochs, seed=0). At each of the epochs epochs, take current iterate as reference , save it in list refs, compute = full_grad(x_ref) and take m steps with i = rng.integers(n) and , , 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 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, refsSummary
- On an -smooth nonconvex function, SGD with satisfies . With optimal step, finding an -stationary point costs 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 times an exponential gradient average: effective step , noise reduced to and lag steps. With dominant noise it is equivalent to SGD with step .
- Stationary SGD loss is approximately , and each direction equilibrates in roughly steps. Thus high reduces bias, final decay reduces variance almost immediately, and loss falls in steps.
- Warmup follows the stability limit , 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 , 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.