Stochastic optimization and SGD
Formulate learning as minimization of an expectation or finite sum and introduce stochastic gradient descent as Robbins–Monro stochastic approximation. Analyze minibatch noise, prove SGD rates for convex and strongly convex problems, and explain the constant-step noise ball and Polyak–Ruppert averaging.
After this lesson you can
- Formulate expectation and finite-sum problems and construct unbiased gradient estimators.
- Calculate minibatch-gradient variance, its 1/B scaling and gradient noise scale.
- Prove the O(1/√T) rate of SGD for convex functions with bounded gradients and O(1/T) for strongly convex functions with decreasing steps.
- Prove that constant-step SGD converges linearly to a region with radius proportional to ησ²/μ.
- Implement SGD with Polyak–Ruppert averaging and verify its advantage empirically.
Before you start
- 06O(1/k) rate of gradient descent for smooth convex functionsLinear convergence of gradient descent for strongly convex functionsDescent lemmaSubgradient methodConvergence orders and ratesGradient descent
- 04Conditional expectationLaw of total varianceVariance of sumsWeak law of large numbersStrong law of large numbers
Motivation: an exact gradient is a luxury
Gradient descent in the earlier lessons takes steps using the exact objective gradient. In machine learning that objective is almost always an average of losses, one per example, and its exact gradient costs individual gradients. With examples, a single iteration costs a million evaluations, and GD needs tens or hundreds of iterations. But consider what that gradient contains: the average of a million vectors which, in early iterations, point mostly in the same direction. To know which way to descend, looking at a few suffices. Estimating the gradient with one randomly selected example gives a noisy vector, but its mean over the choice of example is the exact gradient, at times lower cost.
That is stochastic gradient descent (SGD): at each step, choose one example (or a handful, a minibatch) at random and step using its gradient. The difficult part is not programming it, which takes four lines, but understanding the tradeoffs. Noise means we can no longer say that every step decreases the objective, that a constant step converges to a point, or that comparing methods by iterations makes sense. Three questions guide this lesson. At what rate does SGD converge, and what role does gradient variance play? What happens with a constant step, and how can we fix it (decreasing the step or averaging iterates)? How large should the batch be?
Before formalizing anything, watch the race. The figure pits GD against single-example SGD and minibatch SGD on logistic regression, comparing them by what matters for cost: how many individual gradients have been evaluated.
Take this from the figure. At moderate accuracy SGD wins by a factor increasing with : each noisy gradient costs of the exact one and nearly all early progress follows their common direction. At high accuracy GD wins because it converges linearly, while SGD, with the decreasing step needed to extinguish noise, converges only as . The crossover depends on and curvature, so there is no universal answer: this lesson’s theory explains where it is and why. Neural network training almost always needs moderate accuracy (training loss need not reach , and getting that far often does not improve generalization), which is why SGD and its variants power deep learning.
Expectation or finite sum: the same problem
There are two ways to write what we want to minimize, the second being a special case of the first.
The two sides of the definition correspond to different settings. In expectation form, is a new datum from the world (an email, an image, a self-play game) and is the risk of statistical learning theory (module 13), never computed because it would require knowing : we can only sample. In finite-sum form, the data are fixed and an exact gradient exists, but costs evaluations; choosing at random gives an unbiased oracle at the cost. Unbiasedness is trivial for finite sums, , and in the general form requires exchanging gradient and expectation, valid by dominated convergence when is dominated by an integrable function of locally in .
Analyzing SGD requires assumptions on noise; the three we use must be distinguished because they are not interchangeable.
- (H1) Smoothness and curvature. is -smooth (smoothness) and, when stated, -strongly convex, with .
- (H2) Bounded variance. for every . It measures noise around the true gradient and vanishes if all have the same gradient.
- (H3) Bounded second moment. for every . This is stronger: it bounds the entire gradient, not just noise. It is needed without smoothness (the subgradient case).
(H2) and (H3) are related by variance decomposition, , valid because has zero mean. But (H3) and strong convexity are incompatible over all : if is -strongly convex, is unbounded. Thus the convex case uses (H3), the strongly convex case (H2) with smoothness. Be honest about (H2) from the outset: in least squares one example’s gradient is and its variance grows as away from optimum (unless all coincide), so no uniform exists over the whole space. In logistic regression, by contrast, an example’s loss gradient is at most and (H2) holds with for bounded data (the regularizer’s term is common to all examples and adds no variance). The lesson’s bounds hold where (H2) holds (or on a bounded set containing the iterates) and are the standard way to understand the phenomenon; analysis using the variance at the optimum, which is finite, appears in the handbook by Garrigos and Gower (arXiv:2301.11235).
The SGD step and the Robbins–Monro conditions
In 1951 Robbins and Monro posed a problem more general than minimization. A function is unknown and only noisy observations with are available; the goal is a root . The idea is to step against the observation; the question is how to choose steps.
Each condition guards against a different failure. The first, , guarantees reach: if the starting point is distance from optimum and the gradient has bounded size, the method must be able to travel that distance; with it would remain forever a positive distance away (proved below for the strongly convex case). The second, , guarantees finite accumulated noise: each step injects a perturbation with variance proportional to , and total variance must be finite so it does not keep the iterate wandering. With a constant step, and noise accumulates to an equilibrium level, the noise ball below. With both hold, and with only the first, a case discussed below.
Let be the information from samples . The iterate is determined by it, and since is independent of , the gradient’s conditional expectation is the true gradient: . The entire analysis hangs on an identity which is gradient descent’s stochastic twin. Expanding the square and conditioning,
The second term is the signal: it uses the true gradient and, if is convex, is negative and pushes toward the optimum. The third is noise: always positive, of order . Signal of order and noise of order explain why a small step matters: for small the signal wins, and so is needed to extinguish noise. But a small step makes little progress per iteration, giving the other condition .
Minibatches: variance, batch size and noise scale
A gradient’s noise can be reduced by averaging several. Before the theory, see what a minibatch gradient really looks like at a fixed point.
The figure shows three things the next theorem turns into equations. Histogram mean is the true gradient (unbiasedness). Its width decreases with , but slowly. Distribution shape depends on the data: with small , a few rare examples dominate the tails. For notation, is the covariance matrix of one example’s gradient and the total variance in (H2).
Proof
(1) The are independent and zero-mean, so cross terms in vanish: for (variance of a sum). This leaves .
(2) Let , with , and indicate whether is in the batch, so . We have and, for , . Then
Since and , this gives . Divide by .
∎Thus minibatch gradient variance is : standard deviation falls as . Reducing noise by 10 requires multiplying batch size by 100, and each extra example contributes less than the last: this is the law of large numbers at its rate. The factor without replacement is the finite population correction; it matters only when is an appreciable fraction of (with the gradient is exact and variance vanishes).
The remaining practical question is: how large a batch is worth using? Increasing reduces noise but multiplies the cost of each step. The next result answers from the expected progress of one step. Define as the ratio of total variance of one example’s gradient to the squared true gradient: approximately how many examples are needed for signal and noise to match.
Proof
By the descent inequality, . Take expectation: and, by variance decomposition, . The bound is a parabola in with minimum at ; substitution gives , rewritten as stated.
∎Two consequences for cost. The number of steps needed for a fixed total decrease is proportional to . The number of individual gradients, per step, is proportional to . If , doubling the batch halves the number of steps and leaves gradient cost nearly unchanged: the perfect scaling region, where a larger batch is free if parallelized. If , step count barely falls (approaching its minimum, ) and cost grows linearly with : each extra example is wasted. Thus is the critical batch: McCandlish and colleagues (arXiv:1812.06162) measured it in real networks, and it guides how many accelerators make sense for data parallelism. A naming caution: that paper calls this simple scale and reserves for the curvature-weighted version, , measured in the code. A warning the previous figure hinted at: is not constant. As training advances while does not vanish, so grows, and is infinite at the minimum. The code below measures its growth in logistic regression and checks the law .
Convex objectives: the average’s rate
Identity (1) gives the first convergence result. We work without smoothness, only convexity and (H3), and average iterates (the next section explains why). If is nondifferentiable, is a stochastic subgradient: , and the proof is literally that of the subgradient method with an expectation in front.
Proof
Take expectation in (1) and use convexity, , and (H3): . Summing from to telescopes the distance terms, and since ,
By Jensen’s inequality, , and dividing by gives the first bound. With both terms equal .
∎The rate of SGD for convex objectives has three interpretations. First is bias and variance: is the cost of being far from optimum (decreasing with ) and is the cost of noise (increasing with ); the optimal step balances them. Second, the rate does not depend on or : reducing error to requires individual gradients, regardless of example count. Compare the bound for GD: GD needs iterations of gradients each, or total. The bounds say SGD wins whenever is not very small relative to , the theoretical reason for the first figure’s crossover. Third, cannot be improved with a noisy oracle in the convex class: the stochastic complexity lower bound has the same order (Nemirovski and Yudin; Agarwal and colleagues, 2012), even if is smooth: with an exact oracle Nesterov reaches for smooth convex problems, but with a noisy one the term is unavoidable.
With smoothness as well, noise and curvature separate and the result improves qualitatively.
Proof
From identity (1), with (because by the descent lemma) and convexity,
With , . Sum and apply Jensen as before: . If is the minimum, then and the bound is ; otherwise and it is . In both cases, .
∎Look at the bound: a term identical to GD’s (the deterministic part, of order ) plus a noise term , dominating after a few iterations. With (all individual gradients agree) GD is recovered. A minibatch of size replaces by , but costs gradients per step: in terms of gradients , the bound is , so noise no longer depends on and the deterministic part worsens with it. Batching helps time if parallelizable, not gradient count.
Strongly convex objectives: constant step, noise ball and decreasing step
Strong convexity reveals something hidden by the general case: distance to optimum contracts each step, and a one-line recurrence governs everything.
The proof starts from (1) and uses three facts: (strong convexity), (smoothness) and variance decomposition. It is the first exercise, step by step. The key is reading the recurrence. It is GD’s , with additive term exactly equal to noise injected each step. Contraction plus injection: the recipe for a process with an equilibrium level.
Proof
Unroll the recurrence: , and the geometric sum is bounded by .
∎The first term is GD’s and forgets the starting point at linear rate . The second, , is a plateau: mean squared error does not fall below that level, which grows with step size and noise and decreases with curvature. This is the noise ball, and the bound has the right order. To see it, calculate the exact equilibrium on a quadratic with additive noise, , . By the law of total variance conditioned on , : existing iterate dispersion (contracted by the step) plus noise injected by this step. At equilibrium, in ‘s eigenvector basis (with , variance per coordinate), each direction satisfies , that is,
For small this is , half the general bound: in a direction with and all variance there, versus . The figure makes it visible.
Read three properties from the figure. The plateau is proportional to , because noise per step is and contraction is : doubling the batch and halving the step are equivalent for noise. But not for time: forgetting the start takes steps, so halving doubles that time, while doubling does not change it (but doubles the cost per step). The cloud is not round. Stationary covariance in the direction with eigenvalue is : proportional to , so the cloud stretches along the flat valley direction, where the gradient has least force to return the iterate. And with a decreasing step the ball shrinks to the optimum, but the step must fall to the scale of the flat direction, which takes time for large (change and see).
The practical consequence is the linear scaling rule: the plateau depends on and forgetting time on . Multiplying and by leaves the plateau unchanged, divides steps by , and leaves gradient count ( per step) unchanged: a batch times larger with a step times larger does the same in times fewer steps. The rule runs out when reaches the stability limit or exceeds , exactly as the previous result shows.
To reach the optimum rather than its neighborhood, the step must decrease. Robbins–Monro provides the recipe with a careful choice.
Proof
Write , so and (nonnegative since ). The recurrence gives . Multiply by :
Since , the coefficient of on the left is with , and that on the right is . Using leaves . Summing from to , . Divide by and use (and likewise with ) and .
∎The result has two phases. For the first term dominates: the method must wait for the step to fall enough, and the start is forgotten as . Then dominates, error falling as with a constant independent of the start. This is the stochastic version of GD’s linear convergence, and the price of noise is going from linear rate to sublinear rate . The code below checks this with simulated replicas, with slope on a log-log scale. The schedule contains , and that matters: with on scalar quadratic , decays as , so if mean squared error falls only as , much slower than (Nemirovski, Juditsky, Lan and Shapiro, 2009, note this as the chief fragility of steps). The theorem takes , with , and the first figure . Underestimating worsens only the constant; overestimating it can break the rate. That is optimal in this class is another result of stochastic optimization complexity theory (the same by Agarwal and colleagues); we take it as given here.
The recurrence also shows what the Robbins–Monro conditions guarantee, and how much of them is needed.
Proof
Given , choose such that for . Then , and subtracting from both sides gives . By induction, , because the sum diverges. Thus for every . Conversely, for scalar quadratic with zero-mean and independent of , the cross term vanishes and ; and, since , if and only if .
∎Notice the nuance. Under strong convexity and suffice, and a step, violating , converges in mean square; moreover, with mean squared error falls as , slower than the optimal step’s : this is the slope we measure. The condition is needed when strong convexity is absent, for almost sure convergence in general (via the Robbins–Siegmund lemma, 1971, covered in advanced probability), and is how texts state it. In practice nobody rigidly applies : schedules decrease enough without reaching zero, the subject of the next lesson.
Averaging the noise: Polyak and Ruppert
A decreasing step suppresses noise but raises a problem: how much and when should it decrease? A step decreasing too early makes the method slow because is small; one decreasing late leaves a high plateau (the classic mistake below). Polyak and Ruppert independently proposed a different way out in the late 1980s: leave the step alone and average iterates.
The average already appeared as the iterate with guarantees in the convex theorems. See why it is so powerful for strongly convex problems, with an exact calculation on a quadratic, a model of what happens near a minimum.
Proof
Summing from to telescopes the left side, leaving . Solve for and multiply by . The bound follows from and independence, which gives .
∎Look at the second term. Average error has a noise part, , decaying as and independent of , and a start-up part decaying as , much faster. Compare the last iterate, which cannot fall below the plateau . Two consequences. First, with averaging a constant step can be large without penalty to final variance (only is needed and, to forget the start quickly, not too small). Second, the constant cannot be improved: it is the covariance a maximum-likelihood estimator observing with Gaussian noise of covariance would achieve (its Fisher information is ), the Cramér–Rao limit. Polyak and Juditsky (1992) proved this remains true for nonquadratic, strongly convex, smooth , with steps for : converges in distribution to a Gaussian with covariance , where is the Hessian at . The general case is not proved here.
Tail averaging resolves the figure’s tradeoff. Averaging the whole trajectory carries early iterates far from optimum, with bias decaying as . Tail averaging discards them and therefore forgets the start much sooner, at the cost of averaging fewer iterates (its noise floor is ). The most common rule is to average the last half, or last fraction , of iterates. Rakhlin, Shamir and Sridharan (2012) show that for nonsmooth strongly convex objectives with steps, suffix averaging reaches the previous section’s rate, while averaging the full trajectory can lose a factor ; the last iterate also loses it in that nonsmooth case (Shamir and Zhang, 2013, gave the bound, and Harvey and colleagues, 2019, showed it cannot be improved). In deep networks this returns as exponential moving average of weights (EMA) and stochastic weight averaging, covered in the training module.
With and without replacement: shuffled epochs
So far each gradient comes from a fixed distribution, with replacement. Almost nobody trains this way. Usually the examples are shuffled, traversed one at a time (or in batches) until exhausted, reshuffled and a new epoch starts. This without-replacement sampling is random reshuffling (RR), and is what DataLoader(shuffle=True) does.
The distinction is subtle. Within an epoch gradients are not independent or unbiased conditional on the past: if examples have already been seen, the next is chosen among those remaining, and . This complicates analysis. In exchange it has a geometric advantage: if the iterate were frozen, the sum of an epoch’s gradients would be exactly , without sampling error, whereas with replacement the sum has variance . Noise cancels within the epoch. Mishchenko, Khaled and Richtárik (arXiv:2006.05988) prove this rigorously when each is strongly convex and smooth (and with worse constants when only is): with sufficiently small constant step , RR mean squared error at each epoch’s end stabilizes at order , where is individual-gradient variance at optimum, versus for SGD with replacement; and with decreasing step it beats SGD with replacement after enough epochs. The code below measures this on a small example. In the single-pass regime of large language models, the distinction disappears: each example is seen once, so each gradient is a fresh sample from the data distribution and SGD directly optimizes the expectation-form risk without treating the training set as finite.
Implementation from scratch
Start with generic SGD. It takes grad_i(x, idx), returning the mean gradient of examples idx (including the regularizer, so it is unbiased for the full gradient), a schedule schedule(k), and returns iterates or their averages. The problem is regularized logistic regression with , and ; Newton finds the minimum to provide an exact reference .
import numpy as np
rng = np.random.default_rng(0)
n, d, lam = 2000, 10, 0.01
Z = rng.normal(size=(n, d)) * 0.85 ** np.arange(d)
Z[:, -1] = 1.0 # término independiente
w_true = rng.normal(size=d)
y = np.where(rng.random(n) < 1 / (1 + np.exp(-Z @ w_true)), 1.0, -1.0)
def loss(w):
return np.mean(np.logaddexp(0, -y * (Z @ w))) + 0.5 * lam * w @ w
def grad_i(w, idx):
"""Gradiente medio de los ejemplos idx (regularizador incluido): insesgado para el gradiente completo."""
s = y[idx] * (Z[idx] @ w)
c = -y[idx] * 0.5 * (1 - np.tanh(s / 2)) # -y sigmoide(-s), estable
return Z[idx].T @ c / len(idx) + lam * w
w = np.zeros(d)
for _ in range(30): # Newton: w* y f* de referencia
p = 0.5 * (1 - np.tanh(y * (Z @ w) / 2))
H = Z.T @ ((p * (1 - p))[:, None] * Z) / n + lam * np.eye(d)
w = w - np.linalg.solve(H, grad_i(w, np.arange(n)))
fstar = loss(w)
mu = lam
L = np.linalg.eigvalsh(Z.T @ Z / n)[-1] / 4 + lam
Lmax = (Z ** 2).sum(1).max() / 4 + lam # suavidad del peor ejemplo
print(f"n = {n}, mu = {mu}, L = {L:.3f}, L_max = {Lmax:.2f}, kappa = {L / mu:.1f}, f* = {fstar:.5f}")
def sgd(grad_i, n, x0, schedule, batch=1, steps=1000, average=False, seed=0):
"""x_{k+1} = x_k - schedule(k) * g_k, con g_k el gradiente de un minibatch (con reemplazo)."""
r = np.random.default_rng(seed)
x = np.array(x0, dtype=float)
xbar = x.copy()
out = [xbar.copy() if average else x.copy()]
for k in range(steps):
idx = r.integers(0, n, size=batch)
x = x - schedule(k) * grad_i(x, idx)
xbar = xbar + (x - xbar) / (k + 2) # media corriente de x_0, ..., x_{k+1}
out.append(xbar.copy() if average else x.copy())
return np.array(out)
K0 = int(np.ceil(2 * Lmax / mu))
schedules = {
"constante 0.5/Lmax": lambda k: 0.5 / Lmax,
"c/sqrt(k+1)": lambda k: 1.5 / Lmax / np.sqrt(k + 1),
"2/(mu(k+K0))": lambda k: 2 / (mu * (k + K0)),
}
T = 4000
marks = [100, 1000, T]
print(f"\nf(x_k) - f* tras k = {marks} gradientes (una réplica)")
for name, sc in schedules.items():
last = sgd(grad_i, n, np.zeros(d), sc, steps=T, seed=1)
avg = sgd(grad_i, n, np.zeros(d), sc, steps=T, seed=1, average=True)
print(f"{name:20s} último: " + " ".join(f"{loss(last[k]) - fstar:.1e}" for k in marks) + " | promedio: " + " ".join(f"{loss(avg[k]) - fstar:.1e}" for k in marks))Each gradient costs the same across methods, so is also the number of evaluated gradients. With constant step, the last iterate stays in its noise ball: is at and at , with no improvement, while its average keeps falling ( and ), about 14 times better than the final last iterate. With schedule , with (calibrated to worst-example smoothness , not ), the last iterate reaches and the average . With averaging the entire trajectory worsens the last iterate ( versus ): it drags along early distant iterates, and the decreasing step does not compensate. These numbers are from one replica and vary with seed, but the trend (averaging is the tool for constant or nearly constant steps, decreasing steps for the last iterate) matches theory.
The second cell verifies theorems in a case where they can be calculated exactly: a quadratic with additive Gaussian noise, simulated using 1500 parallel replicas to estimate expectation. It measures error slope on a log-log scale, the constant-step plateau against , and the decreasing-step theorem’s bound.
lam_q = np.geomspace(1.0, 20.0, 5) # mu = 1, L = 20
mu_q, L_q = lam_q[0], lam_q[-1]
kappa_q = L_q / mu_q
sigma2 = 4.0
R, Tq = 1500, 1500 # réplicas independientes y pasos
x0q = np.full(5, 2.0)
a0 = x0q @ x0q
K0q = int(np.ceil(2 * kappa_q))
def run(schedule, seed=0):
"""Error cuadrático medio E||x_k||^2 de R réplicas en paralelo, k = 0..Tq."""
r = np.random.default_rng(seed)
x = np.tile(x0q, (R, 1))
msd = [a0]
for k in range(Tq):
noise = r.normal(size=x.shape) * np.sqrt(sigma2 / 5)
x = x - schedule(k) * (lam_q * x + noise)
msd.append(np.mean(np.sum(x * x, axis=1)))
return np.array(msd)
eta_c = 0.05
runs = {
"constante": run(lambda k: eta_c),
"1/sqrt(k)": run(lambda k: 0.5 / np.sqrt(k + 1)),
"2/(mu(k+K0))": run(lambda k: 2 / (mu_q * (k + K0q))),
}
ks = np.arange(Tq + 1)
print("pendiente de log E||x_k||^2 frente a log k, entre k = 150 y k = 1500")
for name, m in runs.items():
slope = np.polyfit(np.log(ks[150:]), np.log(m[150:]), 1)[0]
print(f" {name:14s} {slope:6.2f}")
meseta = np.sum(eta_c * (sigma2 / 5) / (lam_q * (2 - eta_c * lam_q)))
print(f"\nmeseta medida {runs['constante'][-1]:.4f} meseta teórica {meseta:.4f}")
m = runs["2/(mu(k+K0))"]
cota = (K0q / (ks + K0q)) ** 2 * a0 + 4 * sigma2 / (mu_q ** 2 * np.maximum(ks, 1))
print(f"max_k E||x_k - x*||^2 / cota = {(m[1:] / cota[1:]).max():.3f} (el teorema dice <= 1)")
print(f"k E||x_k||^2 en k = {Tq}: {Tq * m[Tq]:.2f} frente a 4 sigma^2/mu^2 = {4 * sigma2 / mu_q ** 2:.1f}")The three slopes are those predicted: for constant step (a plateau), for and for . The measured plateau, , agrees with theoretical within Monte Carlo error (a few percent with 1500 replicas). The theorem’s bound holds for every with slack factor 3.4 (maximum ratio ), and the asymptotic value of is , nine times smaller than : the bound uses the worst case with all noise in the curvature direction, while here noise is spread over five directions with curvatures from to .
The third cell measures noise scale in the first logistic regression. It computes gradients of all examples, , and during GD training, then checks by measuring for each batch size the expected decrease of one step using the best on a grid. Alongside the simple scale , it computes the curvature-weighted scale , exact for a quadratic: it follows from the theorem’s calculation using .
def per_example_grads(w):
s = y * (Z @ w)
return (-y * 0.5 * (1 - np.tanh(s / 2)))[:, None] * Z + lam * w
def hessian(w):
p = 0.5 * (1 - np.tanh(y * (Z @ w) / 2))
return Z.T @ ((p * (1 - p))[:, None] * Z) / n + lam * np.eye(d)
def noise_scale(w):
"""B_noise = tr(Sigma)/||grad||^2 (simple) y tr(H Sigma)/(g^T H g) (ponderada por la curvatura)."""
G = per_example_grads(w)
g = G.mean(axis=0)
Sigma = (G - g).T @ (G - g) / n
H = hessian(w)
return np.trace(Sigma) / (g @ g), np.trace(H @ Sigma) / (g @ H @ g), g @ g, np.trace(Sigma)
w = np.zeros(d)
print("iter f - f* |grad|^2 tr(Sigma) B_simple B_H")
snaps = {}
for it in range(31): # GD con paso 1/L
if it in (0, 2, 5, 10, 30):
bs, bh, gn, tr = noise_scale(w)
snaps[it] = w.copy()
print(f"{it:4d} {loss(w) - fstar:9.2e} {gn:10.2e} {tr:9.3f} {bs:9.1f} {bh:9.1f}")
w = w - grad_i(w, np.arange(n)) / L
def best_gain(w, B, etas, draws=200, seed=0):
"""Bajada esperada de f en un paso, con el mejor eta de la cuadrícula (draws minibatches a la vez)."""
r = np.random.default_rng(seed)
idx = r.integers(0, n, size=(draws, B))
s = y[idx] * (Z[idx] @ w)
c = -y[idx] * 0.5 * (1 - np.tanh(s / 2))
g = np.einsum("db,dbj->dj", c, Z[idx]) / B + lam * w # un gradiente de minibatch por fila
f0, best = loss(w), 0.0
for eta in etas:
W = w - eta * g
f_new = np.mean(np.logaddexp(0, -y[:, None] * (Z @ W.T)), axis=0) + 0.5 * lam * np.sum(W * W, axis=1)
best = max(best, f0 - f_new.mean())
return best
etas = np.geomspace(0.05, 12, 9)
Bs = [1, 4, 16, 64, 256, 1024]
for it in (0, 5):
w = snaps[it]
bs, bh, _, _ = noise_scale(w)
gains = np.array([best_gain(w, B, etas) for B in Bs])
print(f"\nen la iteración {it}: B_simple = {bs:.0f}, B_H = {bh:.0f}")
print(" B ganancia/ganancia(1024) ley 1/(1+B_simple/B) ley 1/(1+B_H/B)")
for B, gv in zip(Bs, gains):
print(f"{B:5d} {gv / gains[-1]:10.3f} {(1 / (1 + bs / B)) / (1 / (1 + bs / Bs[-1])):14.3f} {(1 / (1 + bh / B)) / (1 / (1 + bh / Bs[-1])):14.3f}")The first table measures the minibatch section’s warning. From GD iteration 0 to 30, falls from to , while falls only from to : simple noise scale rises from to over . Initially a small batch suffices for signal to dominate, and later noise dominates completely, so critical batch size grows during training, motivating schedules that increase . The second table checks the law. At iteration 0, the decrease with the best step for each , normalized by that at , follows : with measured versus predicted (simple) and (weighted); with , versus and . At iteration 5, curvature-weighted scale reproduces data almost exactly ( measured versus with ), while simple overestimates it (): noise in flat directions is less harmful than the simple trace suggests. The simple scale gives order of magnitude, off by a small factor, and the weighted one is exact for a quadratic.
The last cell compares sampling with and without replacement on least squares with 50 examples and noisy labels (no interpolation, so SGD noise does not vanish at the optimum). Start at to measure the noise floor directly, with 400 parallel replicas, and inspect error at the end of each epoch.
r0 = np.random.default_rng(3)
n_, d_ = 50, 4
A = r0.normal(size=(n_, d_))
b = A @ np.ones(d_) + r0.normal(size=n_) # ruido: no hay interpolación
xs = np.linalg.lstsq(A, b, rcond=None)[0] # mínimo de F(x) = (1/2n) sum (a_i x - b_i)^2
R_, epochs = 400, 40
def final_error(eta, reshuffle, seed=0):
rr = np.random.default_rng(seed)
x = np.tile(xs, (R_, 1)) # se arranca en x*: se mide el suelo de ruido
err = []
for e in range(epochs):
if reshuffle:
order = np.argsort(rr.random((R_, n_)), axis=1) # una permutación por réplica
else:
order = rr.integers(0, n_, size=(R_, n_)) # n índices con reemplazo
for t in range(n_):
a = A[order[:, t]]
x = x - eta * (np.sum(a * x, axis=1) - b[order[:, t]])[:, None] * a
if e >= epochs // 2:
err.append(np.mean(np.sum((x - xs) ** 2, axis=1))) # al final de cada época
return np.mean(err)
print(" eta SGD con reemplazo barajado (RR) cociente")
rows = []
for eta in (0.04, 0.02, 0.01):
s_, rr_ = final_error(eta, False), final_error(eta, True)
rows.append((eta, s_, rr_))
print(f"{eta:6.3f} {s_:14.3e} {rr_:14.3e} {s_ / rr_:8.1f}")
print("al bajar eta a la mitad: SGD", round(rows[0][1] / rows[1][1], 2), "veces menos; RR", round(rows[0][2] / rows[1][2], 2), "veces menos")Halving the step decreases SGD’s with-replacement noise floor by about times (nearly linearly in ), and the shuffled floor by times, approaching factor of the law: from to , SGD improves times and RR . At shuffling is times more accurate than sampling with replacement at the same gradients per epoch. This is the effect of within-epoch noise cancellation; in real problems the advantage depends on , curvature and shuffling, so this small example illustrates only the order.
The professional version: PyTorch
PyTorch has no separate “stochastic SGD”: the data loop supplies stochasticity and the optimizer only takes the step. The three pieces of this lesson have direct equivalents.
| What you need | Option | Note |
|---|---|---|
| Step | torch.optim.SGD(params, lr) | Without momentum this is exactly the lesson’s formula; loss.backward() computes the minibatch gradient. |
| Shuffled epochs (without replacement) | DataLoader(dataset, batch_size=B, shuffle=True) | A new permutation each epoch. With drop_last=False the last batch may be smaller. |
| Sampling with replacement | RandomSampler(dataset, replacement=True) or WeightedRandomSampler | The analysis model; useful for differently weighted examples. |
| Polyak–Ruppert averaging | torch.optim.swa_utils.AveragedModel | Call update_parameters(model) after each step (or epoch); the default is the arithmetic mean. |
| Step schedule | torch.optim.lr_scheduler.* | The subject of the next lesson. |
The next cell checks three exact equivalences on a tiny problem (CPU, float64).
import numpy as np, torch
from torch.utils.data import DataLoader, TensorDataset
torch.set_default_dtype(torch.float64)
torch.set_num_threads(1)
g = torch.Generator().manual_seed(0)
n, d = 12, 3
X = torch.randn(n, d, generator=g)
yv = X @ torch.tensor([1.0, -2.0, 0.5]) + 0.1 * torch.randn(n, generator=g)
# 1) Una época de DataLoader(shuffle=True) visita cada ejemplo exactamente una vez
ds = TensorDataset(X, yv, torch.arange(n))
dl = DataLoader(ds, batch_size=4, shuffle=True, generator=torch.Generator().manual_seed(1))
for ep in range(3):
visitados = torch.cat([b[2] for b in dl]).sort().values
print(f"época {ep}: cada ejemplo una vez ->", bool((visitados == torch.arange(n)).all()))
# 2) torch.optim.SGD sin momentum es x <- x - lr * g
w = torch.zeros(d, requires_grad=True)
opt = torch.optim.SGD([w], lr=0.1)
w_ref = np.zeros(d)
for xb, yb, _ in DataLoader(ds, batch_size=4, shuffle=False):
opt.zero_grad()
(0.5 * ((xb @ w - yb) ** 2).mean()).backward()
opt.step()
gref = xb.numpy().T @ (xb.numpy() @ w_ref - yb.numpy()) / 4
w_ref = w_ref - 0.1 * gref
print("SGD de PyTorch frente a la fórmula:", np.abs(w.detach().numpy() - w_ref).max())
# 3) AveragedModel es la media corriente de los iterados
model = torch.nn.Linear(d, 1, bias=False)
torch.nn.init.zeros_(model.weight)
swa = torch.optim.swa_utils.AveragedModel(model)
opt = torch.optim.SGD(model.parameters(), lr=0.05)
iterados = []
for xb, yb, _ in DataLoader(ds, batch_size=3, shuffle=True, generator=torch.Generator().manual_seed(2)):
opt.zero_grad()
(0.5 * ((model(xb).squeeze(1) - yb) ** 2).mean()).backward()
opt.step()
swa.update_parameters(model)
iterados.append(model.weight.detach().clone().flatten().numpy())
print("AveragedModel frente a la media de los iterados:", np.abs(swa.module.weight.detach().flatten().numpy() - np.mean(iterados, axis=0)).max())npm run lab and open the connection link.The first three lines say True: each DataLoader epoch is a permutation. The two differences are on the order of , rounding: torch.optim.SGD without momentum is the lesson’s formula, and AveragedModel is the running mean of iterates (programmed manually in sgd(..., average=True)). Sampling, and thus minibatch gradient unbiasedness, is determined by the data loop, not the optimizer.
Common mistakes
Exercises
Step 1 of 4. After expanding and conditioning, what bound follows for ?
Step 1 of 3. Which property of bounds the cross term?
sgd(grad_i, n, x0, schedule, batch=1, steps=1000, average=False, sampling='replace', seed=0), returning an array of shape (steps + 1, d) with x_0, ..., x_steps (or their Polyak–Ruppert averages xbar_k = media de x_0..x_k if average=True). Each step uses grad_i(x, idx) (mean gradient of examples idx), and schedule(k) is the step at iteration k = 0, 1, .... With sampling='replace', idx consists of batch indices sampled with replacement; with sampling='shuffle', examples are traversed in epochs: shuffle a permutation of 0..n-1 and take consecutive batches of size batch, reshuffling once exhausted (assume batch divides n). Use np.random.default_rng(seed) only for drawing indices.import numpy as np
def sgd(grad_i, n, x0, schedule, batch=1, steps=1000, average=False, sampling='replace', seed=0):
"""Iterados (o promedios) de SGD con muestreo con reemplazo o por épocas barajadas."""
rng = np.random.default_rng(seed)
x = np.array(x0, dtype=float)
out = [x.copy()]
for k in range(steps):
# tu código: elegir idx según 'sampling', dar el paso y mantener el promedio corriente
x = x - schedule(k) * grad_i(x, np.arange(n))
out.append(x.copy())
return np.array(out)Summary
- The objective is an expectation or its finite-sum case, and the stochastic oracle is unbiased. Noise assumptions (H2) bounded variance and (H3) bounded second moment are not interchangeable, and no uniform exists for least squares.
- SGD steps obey : signal of order , noise of order . Robbins–Monro conditions and ensure enough reach and finite accumulated noise; with , SGD on the mean is the sample mean and its convergence is the law of large numbers.
- Minibatch gradient variance is (with replacement) or (without). Noise scale gives progress per step: with a larger batch is nearly free, while with it is wasted. grows during training.
- For convex objectives, the average satisfies , independent of and ; with smoothness, . For strongly convex objectives, recurrence gives linear convergence to a noise ball with radius at constant step, and with .
- Polyak–Ruppert averaging, leaving the step unchanged, has error independent of on a quadratic; tail averaging discards the start. Shuffled epochs (without replacement) reduce the noise floor from to for smooth strongly convex problems, and are implemented by
DataLoader(shuffle=True). - Always compare by gradients evaluated, not iterations; do not assume Gaussian or isotropic noise; evaluate convergence on a fixed set, not using minibatch loss.