Module contents
Lesson 18 of 27Core 120 min

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

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 nn losses, one per example, and its exact gradient costs nn individual gradients. With n=106n = 10^6 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 nn 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.

InteractiveSame budget, different method
  • GD (full gradient)
  • SGD (1 example)
  • SGD with minibatch, B=32B = 32
  • target accuracy
Examples nn
Regularization λ=μ\lambda = \mu
32
0.50
0.01
Horizontal axis
GD to ε\varepsilon10 000 grad.
SGD to ε\varepsilon775 grad.
Batch B=32B = 32 to ε\varepsilon256 grad.
Condition κ=L/μ\kappa = L/\mu27
SGD needs about 39.1 times fewer gradients than GD for this accuracy. Lower ε\varepsilon until the blue curve crosses the orange one.
Regularized logistic regression (d=10d = 10) with editable nn and λ\lambda. Curves of f−f⋆f - f^\star against individual gradients evaluated (logarithmic scale) for GD with step 1/L1/L, single-example SGD and minibatch SGD, the latter two with ηk=η0/(1+η0μk)\eta_k = \eta_0/(1 + \eta_0\mu k). The dashed line is target accuracy ε\varepsilon and readouts show the gradients needed by each method to reach it. With initial settings (n=2000n = 2000, κ≈27\kappa \approx 27) and ε=10−2\varepsilon = 10^{-2}, GD needs 10,000 gradients, SGD 775 and minibatch 32 needs 256. Lower ε\varepsilon until curves cross: with ε=10−4\varepsilon = 10^{-4} GD needs 48,000 gradients and SGD 74,158. Increase nn and check that the crossover shifts to higher accuracy. Finally change the horizontal axis to “Iterations” and notice the warning: this is the most common mistake in comparing methods.

Take this from the figure. At moderate accuracy SGD wins by a factor increasing with nn: each noisy gradient costs 1/n1/n 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 1/k1/k. The crossover depends on nn 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 10−810^{-8}, 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, ξ\xi is a new datum from the world (an email, an image, a self-play game) and FF is the risk R(θ)R(\theta) of statistical learning theory (module 13), never computed because it would require knowing PP: we can only sample. In finite-sum form, the data are fixed and an exact gradient exists, but costs nn evaluations; choosing ii at random gives an unbiased oracle at 1/n1/n the cost. Unbiasedness is trivial for finite sums, Ei[∇fi(x)]=1n∑i∇fi(x)=∇F(x)\E_i[\grad f_i(\vb{x})] = \frac1n\sum_i\grad f_i(\vb{x}) = \grad F(\vb{x}), and in the general form requires exchanging gradient and expectation, valid by dominated convergence when ∇f(x;ξ)\grad f(\vb{x}; \xi) is dominated by an integrable function of ξ\xi locally in x\vb{x}.

Analyzing SGD requires assumptions on noise; the three we use must be distinguished because they are not interchangeable.

  • (H1) Smoothness and curvature. FF is LL-smooth (smoothness) and, when stated, μ\mu-strongly convex, with κ=L/μ\kappa = L/\mu.
  • (H2) Bounded variance. E∥∇f(x;ξ)−∇F(x)∥2≤σ2\E\norm{\grad f(\vb{x}; \xi) - \grad F(\vb{x})}^2 \le \sigma^2 for every x\vb{x}. It measures noise around the true gradient and vanishes if all f(⋅ ;ξ)f(\cdot\,;\xi) have the same gradient.
  • (H3) Bounded second moment. E∥∇f(x;ξ)∥2≤G2\E\norm{\grad f(\vb{x}; \xi)}^2 \le G^2 for every x\vb{x}. 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, E∥g∥2=∥∇F(x)∥2+E∥g−∇F(x)∥2\E\norm{\vb{g}}^2 = \norm{\grad F(\vb{x})}^2 + \E\norm{\vb{g} - \grad F(\vb{x})}^2, valid because g−∇F\vb{g} - \grad F has zero mean. But (H3) and strong convexity are incompatible over all Rd\R^d: if FF is μ\mu-strongly convex, ∥∇F(x)∥≥μ∥x−x⋆∥\norm{\grad F(\vb{x})} \ge \mu\norm{\vb{x} - \vb{x}^\star} 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 ai(ai⊤x−bi)\vb{a}_i(\vb{a}_i\T\vb{x} - b_i) and its variance grows as ∥x∥2\norm{\vb{x}}^2 away from optimum (unless all aiai⊤\vb{a}_i\vb{a}_i\T coincide), so no uniform σ2\sigma^2 exists over the whole space. In logistic regression, by contrast, an example’s loss gradient is at most ∥ai∥\norm{\vb{a}_i} and (H2) holds with σ2≤max⁡i∥ai∥2\sigma^2 \le \max_i\norm{\vb{a}_i}^2 for bounded data (the regularizer’s λx\lambda\vb{x} 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 MM is unknown and only noisy observations N(x,ξ)N(\vb{x}, \xi) with E[N(x,ξ)]=M(x)\E[N(\vb{x}, \xi)] = M(\vb{x}) are available; the goal is a root M(x⋆)=0M(\vb{x}^\star) = \vb{0}. The idea is to step against the observation; the question is how to choose steps.

Each condition guards against a different failure. The first, ∑ηk=∞\sum\eta_k = \infty, guarantees reach: if the starting point is distance rr from optimum and the gradient has bounded size, the method must be able to travel that distance; with ∑ηk<∞\sum\eta_k < \infty it would remain forever a positive distance away (proved below for the strongly convex case). The second, ∑ηk2<∞\sum\eta_k^2 < \infty, guarantees finite accumulated noise: each step injects a perturbation with variance proportional to ηk2σ2\eta_k^2\sigma^2, and total variance must be finite so it does not keep the iterate wandering. With a constant step, ∑ηk2=∞\sum\eta_k^2 = \infty and noise accumulates to an equilibrium level, the noise ball below. With ηk=1/k\eta_k = 1/k both hold, and with ηk=1/k\eta_k = 1/\sqrt{k} only the first, a case discussed below.

Let Fk\mathcal{F}_k be the information from samples ξ0,…,ξk−1\xi_0, \dots, \xi_{k-1}. The iterate xk\vb{x}_k is determined by it, and since ξk\xi_k is independent of Fk\mathcal{F}_k, the gradient’s conditional expectation is the true gradient: E[gk∣Fk]=∇F(xk)\E[\vb{g}_k \given \mathcal{F}_k] = \grad F(\vb{x}_k). The entire analysis hangs on an identity which is gradient descent’s stochastic twin. Expanding the square and conditioning,

E[∥xk+1−x⋆∥2∣Fk]=∥xk−x⋆∥2−2ηk ⟨∇F(xk),xk−x⋆⟩+ηk2 E[∥gk∥2∣Fk].(1)\E\big[\norm{\vb{x}_{k+1} - \vb{x}^\star}^2 \given \mathcal{F}_k\big] = \norm{\vb{x}_k - \vb{x}^\star}^2 - 2\eta_k\,\inner{\grad F(\vb{x}_k)}{\vb{x}_k - \vb{x}^\star} + \eta_k^2\,\E\big[\norm{\vb{g}_k}^2 \given \mathcal{F}_k\big]. \tag{1}

The second term is the signal: it uses the true gradient and, if FF is convex, is negative and pushes toward the optimum. The third is noise: always positive, of order ηk2\eta_k^2. Signal of order η\eta and noise of order η2\eta^2 explain why a small step matters: for small η\eta the signal wins, and so ηk→0\eta_k \to 0 is needed to extinguish noise. But a small step makes little progress per iteration, giving the other condition ∑ηk=∞\sum\eta_k = \infty.

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.

InteractiveAnatomy of the stochastic gradient
  • Means of 4000 batches
  • Gaussian with same mean and σj2/B\sigma_j^2/B
Data
4
0.60
Component
True gradient ∂jF\partial_j F−2.84·10⁻³
Batch mean−4.83·10⁻³
Theoretical variance σj2/B\sigma_j^2/B0.0106
Measured variance0.0106
Skewness · excess kurtosis0.15 · 3.57
Batches beyond 3σ3\sigma (Gaussian: 0.27%)1.30 %
Noise scale Bnoise=tr⁡Σ/∥∇F∥2B_{\text{noise}} = \operatorname{tr}\Sigma / \|\nabla F\|^221.6
At B=4B = 4 the distribution has heavy tails (excess kurtosis 3.6) and is not Gaussian: rare examples produce gradients far from the mean. Increase BB and watch the central limit theorem smooth it.
Logistic regression with n=3000n = 3000 and d=6d = 6. At w=s w⋆\vb{w} = s\,\vb{w}^\star, draw 4000 minibatches of size BB and plot a histogram of one gradient component, with the Gaussian of the same mean and variance σj2/B\sigma_j^2/B. With initial settings (imbalanced classes, B=4B = 4) measured variance 0.01060.0106 matches theory and excess kurtosis is 3.63.6: tails are heavy. Increase BB and verify variance divides by BB and the bell appears. Then move the point to the minimum, s=1s = 1: the true gradient vanishes but noise does not.

The figure shows three things the next theorem turns into equations. Histogram mean is the true gradient (unbiasedness). Its width decreases with BB, but slowly. Distribution shape depends on the data: with small BB, a few rare examples dominate the tails. For notation, Σ(x)=Cov⁡(∇f(x;ξ))\Sigma(\vb{x}) = \Cov(\grad f(\vb{x}; \xi)) is the covariance matrix of one example’s gradient and σ2(x)=tr⁡ Σ(x)\sigma^2(\vb{x}) = \tr\,\Sigma(\vb{x}) the total variance in (H2).

Proof

(1) The gj−∇\vb{g}_j - \nabla are independent and zero-mean, so cross terms in E∥∑j(gj−∇)∥2\E\norm{\sum_j(\vb{g}_j - \nabla)}^2 vanish: E⟨gi−∇,gj−∇⟩=⟨E[gi−∇],E[gj−∇]⟩=0\E\inner{\vb{g}_i - \nabla}{\vb{g}_j - \nabla} = \inner{\E[\vb{g}_i - \nabla]}{\E[\vb{g}_j - \nabla]} = 0 for i≠ji \ne j (variance of a sum). This leaves Bσ2/B2B\sigma^2/B^2.

(2) Let ui=∇fi−∇\vb{u}_i = \grad f_i - \nabla, with ∑iui=0\sum_i\vb{u}_i = \vb{0}, and si∈{0,1}s_i \in \{0, 1\} indicate whether ii is in the batch, so gˉB−∇=1B∑isiui\bar{\vb{g}}_B - \nabla = \frac1B\sum_i s_i\vb{u}_i. We have E[si]=B/n\E[s_i] = B/n and, for i≠ji \ne j, E[sisj]=B(B−1)n(n−1)\E[s_is_j] = \frac{B(B-1)}{n(n-1)}. Then

E∥∑isiui∥2=Bn∑i∥ui∥2+B(B−1)n(n−1)∑i≠j⟨ui,uj⟩.\E\Big\|\sum_i s_i\vb{u}_i\Big\|^2 = \frac{B}{n}\sum_i\norm{\vb{u}_i}^2 + \frac{B(B-1)}{n(n-1)}\sum_{i \ne j}\inner{\vb{u}_i}{\vb{u}_j}.

Since ∑i≠j⟨ui,uj⟩=∥∑iui∥2−∑i∥ui∥2=−nσ2\sum_{i \ne j}\inner{\vb{u}_i}{\vb{u}_j} = \norm{\sum_i\vb{u}_i}^2 - \sum_i\norm{\vb{u}_i}^2 = -n\sigma^2 and ∑i∥ui∥2=nσ2\sum_i\norm{\vb{u}_i}^2 = n\sigma^2, this gives Bσ2(1−B−1n−1)=Bσ2n−Bn−1B\sigma^2\big(1 - \frac{B-1}{n-1}\big) = B\sigma^2\frac{n - B}{n - 1}. Divide by B2B^2.

∎

Thus minibatch gradient variance is σ2/B\sigma^2/B: standard deviation falls as 1/B1/\sqrt{B}. 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 1/B1/\sqrt{B} rate. The factor (n−B)/(n−1)(n - B)/(n - 1) without replacement is the finite population correction; it matters only when BB is an appreciable fraction of nn (with B=nB = n the gradient is exact and variance vanishes).

The remaining practical question is: how large a batch is worth using? Increasing BB reduces noise but multiplies the cost of each step. The next result answers from the expected progress of one step. Define Bnoise=tr⁡Σ/∥∇F∥2B_{\text{noise}} = \tr\Sigma/\norm{\nabla F}^2 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, F(x+)≤F(x)−η⟨∇,gˉB⟩+Lη22∥gˉB∥2F(\vb{x}^+) \le F(\vb{x}) - \eta\inner{\nabla}{\bar{\vb{g}}_B} + \frac{L\eta^2}{2}\norm{\bar{\vb{g}}_B}^2. Take expectation: E⟨∇,gˉB⟩=∥∇∥2\E\inner{\nabla}{\bar{\vb{g}}_B} = \norm{\nabla}^2 and, by variance decomposition, E∥gˉB∥2=∥∇∥2+tr⁡Σ/B\E\norm{\bar{\vb{g}}_B}^2 = \norm{\nabla}^2 + \tr\Sigma/B. The bound is a parabola in η\eta with minimum at η⋆=∥∇∥2/(L(∥∇∥2+tr⁡Σ/B))\eta^\star = \norm{\nabla}^2/\big(L(\norm{\nabla}^2 + \tr\Sigma/B)\big); substitution gives Δ(B)=∥∇∥4/(2L(∥∇∥2+tr⁡Σ/B))\Delta(B) = \norm{\nabla}^4/\big(2L(\norm{\nabla}^2 + \tr\Sigma/B)\big), rewritten as stated.

∎

Two consequences for cost. The number of steps needed for a fixed total decrease is proportional to 1/Δ(B)∝1+Bnoise/B1/\Delta(B) \propto 1 + B_{\text{noise}}/B. The number of individual gradients, BB per step, is proportional to B(1+Bnoise/B)=B+BnoiseB(1 + B_{\text{noise}}/B) = B + B_{\text{noise}}. If B≪BnoiseB \ll B_{\text{noise}}, 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 B≫BnoiseB \gg B_{\text{noise}}, step count barely falls (approaching its minimum, ∝1\propto 1) and cost grows linearly with BB: each extra example is wasted. Thus BnoiseB_{\text{noise}} 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 BsimpleB_{\text{simple}} and reserves BnoiseB_{\text{noise}} for the curvature-weighted version, tr⁡(HΣ)/(∇F⊤H∇F)\tr(\mat{H}\Sigma)/(\nabla F\T\mat{H}\nabla F), measured in the code. A warning the previous figure hinted at: BnoiseB_{\text{noise}} is not constant. As training advances ∥∇F∥→0\norm{\nabla F}\to 0 while tr⁡Σ\tr\Sigma does not vanish, so BnoiseB_{\text{noise}} grows, and is infinite at the minimum. The code below measures its growth in logistic regression and checks the law 1/(1+Bnoise/B)1/(1 + B_{\text{noise}}/B).

Convex objectives: the average’s 1/T1/\sqrt{T} 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 FF is nondifferentiable, gk\vb{g}_k is a stochastic subgradient: E[gk∣Fk]∈∂F(xk)\E[\vb{g}_k \given \mathcal{F}_k] \in \partial F(\vb{x}_k), and the proof is literally that of the subgradient method with an expectation in front.

Proof

Take expectation in (1) and use convexity, ⟨∇F(xk),xk−x⋆⟩≥F(xk)−F⋆\inner{\grad F(\vb{x}_k)}{\vb{x}_k - \vb{x}^\star} \ge F(\vb{x}_k) - F^\star, and (H3): E∥xk+1−x⋆∥2≤E∥xk−x⋆∥2−2η E[F(xk)−F⋆]+η2G2\E\norm{\vb{x}_{k+1} - \vb{x}^\star}^2 \le \E\norm{\vb{x}_k - \vb{x}^\star}^2 - 2\eta\,\E[F(\vb{x}_k) - F^\star] + \eta^2G^2. Summing from k=0k = 0 to T−1T - 1 telescopes the distance terms, and since ∥xT−x⋆∥2≥0\norm{\vb{x}_T - \vb{x}^\star}^2 \ge 0,

2η∑k=0T−1E[F(xk)−F⋆]≤R2+Tη2G2.2\eta\sum_{k=0}^{T-1}\E[F(\vb{x}_k) - F^\star] \le R^2 + T\eta^2G^2.

By Jensen’s inequality, F(xˉT)≤1T∑kF(xk)F(\bar{\vb{x}}_T) \le \frac1T\sum_k F(\vb{x}_k), and dividing by 2ηT2\eta T gives the first bound. With η=R/(GT)\eta = R/(G\sqrt{T}) both terms equal RG/(2T)RG/(2\sqrt{T}).

∎

The O(1/T)\bigO(1/\sqrt{T}) rate of SGD for convex objectives has three interpretations. First is bias and variance: R2/(2ηT)R^2/(2\eta T) is the cost of being far from optimum (decreasing with η\eta) and ηG2/2\eta G^2/2 is the cost of noise (increasing with η\eta); the optimal step balances them. Second, the rate does not depend on nn or dd: reducing error to ε\varepsilon requires T=R2G2/ε2T = R^2G^2/\varepsilon^2 individual gradients, regardless of example count. Compare the 1/k1/k bound for GD: GD needs LR2/(2ε)LR^2/(2\varepsilon) iterations of nn gradients each, or nLR2/(2ε)nLR^2/(2\varepsilon) total. The bounds say SGD wins whenever ε\varepsilon is not very small relative to G2/(nL)G^2/(nL), the theoretical reason for the first figure’s crossover. Third, 1/T1/\sqrt{T} 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 FF is smooth: with an exact oracle Nesterov reaches 1/k21/k^2 for smooth convex problems, but with a noisy one the Rσ/TR\sigma/\sqrt{T} term is unavoidable.

With smoothness as well, noise and curvature separate and the result improves qualitatively.

Proof

From identity (1), with E∥gk∥2=∥∇F(xk)∥2+E∥gk−∇F(xk)∥2≤2L(F(xk)−F⋆)+σ2\E\norm{\vb{g}_k}^2 = \norm{\grad F(\vb{x}_k)}^2 + \E\norm{\vb{g}_k - \grad F(\vb{x}_k)}^2 \le 2L\big(F(\vb{x}_k) - F^\star\big) + \sigma^2 (because F⋆≤F(x−∇F/L)≤F(x)−∥∇F∥2/(2L)F^\star \le F(\vb{x} - \grad F/L) \le F(\vb{x}) - \norm{\grad F}^2/(2L) by the descent lemma) and convexity,

E∥xk+1−x⋆∥2≤E∥xk−x⋆∥2−2η(1−ηL) E[F(xk)−F⋆]+η2σ2.\E\norm{\vb{x}_{k+1} - \vb{x}^\star}^2 \le \E\norm{\vb{x}_k - \vb{x}^\star}^2 - 2\eta(1 - \eta L)\,\E[F(\vb{x}_k) - F^\star] + \eta^2\sigma^2.

With η≤1/(2L)\eta \le 1/(2L), 2η(1−ηL)≥η2\eta(1 - \eta L) \ge \eta. Sum and apply Jensen as before: E[F(xˉT)]−F⋆≤R2/(ηT)+ησ2\E[F(\bar{\vb{x}}_T)] - F^\star \le R^2/(\eta T) + \eta\sigma^2. If η=1/(2L)\eta = 1/(2L) is the minimum, then η≤R/(σT)\eta \le R/(\sigma\sqrt{T}) and the bound is ≤2LR2/T+Rσ/T\le 2LR^2/T + R\sigma/\sqrt{T}; otherwise η=R/(σT)\eta = R/(\sigma\sqrt{T}) and it is 2Rσ/T2R\sigma/\sqrt{T}. In both cases, ≤2LR2/T+2Rσ/T\le 2LR^2/T + 2R\sigma/\sqrt{T}.

∎

Look at the bound: a term 2LR2/T2LR^2/T identical to GD’s (the deterministic part, of order 1/T1/T) plus a noise term 2Rσ/T2R\sigma/\sqrt{T}, dominating after a few iterations. With σ=0\sigma = 0 (all individual gradients agree) GD is recovered. A minibatch of size BB replaces σ2\sigma^2 by σ2/B\sigma^2/B, but costs BB gradients per step: in terms of gradients N=BTN = BT, the bound is 2LR2B/N+2Rσ/N2LR^2B/N + 2R\sigma/\sqrt{N}, so noise no longer depends on BB 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: ⟨∇F(x),x−x⋆⟩≥F(x)−F⋆+μ2∥x−x⋆∥2\inner{\grad F(\vb{x})}{\vb{x} - \vb{x}^\star} \ge F(\vb{x}) - F^\star + \frac\mu2\norm{\vb{x} - \vb{x}^\star}^2 (strong convexity), ∥∇F(x)∥2≤2L(F(x)−F⋆)\norm{\grad F(\vb{x})}^2 \le 2L(F(\vb{x}) - F^\star) (smoothness) and variance decomposition. It is the first exercise, step by step. The key is reading the recurrence. It is GD’s ek+1=(1−ημ)eke_{k+1} = (1 - \eta\mu)e_k, with additive term η2σ2\eta^2\sigma^2 exactly equal to noise injected each step. Contraction plus injection: the recipe for a process with an equilibrium level.

Proof

Unroll the recurrence: ak≤(1−ημ)ka0+η2σ2∑j=0k−1(1−ημ)ja_k \le (1 - \eta\mu)^k a_0 + \eta^2\sigma^2\sum_{j=0}^{k-1}(1 - \eta\mu)^j, and the geometric sum is bounded by 1/(ημ)1/(\eta\mu).

∎

The first term is GD’s and forgets the starting point at linear rate 1−ημ1 - \eta\mu. The second, ησ2/μ\eta\sigma^2/\mu, 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 F=12x⊤AxF = \frac12\vb{x}\T\mat{A}\vb{x} with additive noise, xk+1=xk−η(Axk+εk)\vb{x}_{k+1} = \vb{x}_k - \eta(\mat{A}\vb{x}_k + \vb{\varepsilon}_k), Cov⁡(εk)=Σε\Cov(\vb{\varepsilon}_k) = \Sigma_\varepsilon. By the law of total variance conditioned on xk\vb{x}_k, Cov⁡(xk+1)=Cov⁡(E[xk+1∣xk])+E[Cov⁡(xk+1∣xk)]=(I−ηA)Cov⁡(xk)(I−ηA)+η2Σε\Cov(\vb{x}_{k+1}) = \Cov(\E[\vb{x}_{k+1} \given \vb{x}_k]) + \E[\Cov(\vb{x}_{k+1} \given \vb{x}_k)] = (\mat{I} - \eta\mat{A})\Cov(\vb{x}_k)(\mat{I} - \eta\mat{A}) + \eta^2\Sigma_\varepsilon: existing iterate dispersion (contracted by the step) plus noise injected by this step. At equilibrium, in A\mat{A}‘s eigenvector basis (with Σε=sI\Sigma_\varepsilon = s\mat{I}, variance ss per coordinate), each direction satisfies vi=(1−ηλi)2vi+η2sv_i = (1 - \eta\lambda_i)^2v_i + \eta^2s, that is,

vi=η sλi(2−ηλi).v_i = \frac{\eta\,s}{\lambda_i(2 - \eta\lambda_i)}.

For small ηλi\eta\lambda_i this is ηs/(2λi)\eta s/(2\lambda_i), half the general bound: in a direction with λi=μ\lambda_i = \mu and all variance there, ησ2/(2μ)\eta\sigma^2/(2\mu) versus ησ2/μ\eta\sigma^2/\mu. The figure makes it visible.

InteractiveThe noise ball

Dashed: theoretical covariance ellipse at 1.5 standard deviations (constant step).

  • constant step
  • decreasing step
  • theoretical plateau
0.200
4
10
Step schedule
k = 300
E∥xk∥2\mathbb{E}\|\mathbf{x}_k\|^2 measured in cloud0.264
Theoretical plateau (constant step η\eta)0.28
Current step ηk\eta_k0.1995
Plateau ÷ (η/B\eta/B)5.61
The theoretical plateau is ∑iησ2/(Bλi(2−ηλi))\sum_i \eta\sigma^2 / (B\lambda_i (2 - \eta\lambda_i)). For small η\eta it is proportional to η/B\eta/B: doubling the batch or halving the step halves the squared radius. The ellipse stretches along the flat direction (λi=1/κ\lambda_i = 1/\kappa).
Three hundred particles run SGD in parallel on quadratic F=12x⊤AxF = \tfrac12\vb{x}\T\mat{A}\vb{x} with eigenvalues 11 and 1/κ1/\kappa, gradients Ax+ζ\mat{A}\vb{x} + \zeta, ζ∼N(0,(σ2/B)I)\zeta \sim \Normal(\vb{0}, (\sigma^2/B)\mat{I}) and σ=1\sigma = 1. All start at the same point. The dashed ellipse is theoretical stationary covariance. With initial settings (η≈0.2\eta \approx 0.2, B=4B = 4, κ=10\kappa = 10) the theoretical E∥x∥2\E\|\vb{x}\|^2 plateau is 0.2800.280 and the cloud measures 0.2640.264. Double BB or halve η\eta: the plateau falls to 0.1400.140 and 0.1390.139, nearly half in both cases. Notice the cloud stretching in the lowest-curvature direction. Then switch to decreasing, the first figure's ηk=η/(1+ημk)\eta_k = \eta/(1 + \eta\mu k) schedule, and play: the cloud closes on the optimum, and E∥x300∥2\E\|\vb{x}_{300}\|^2 falls to 0.0700.070 instead of plateauing. With κ=100\kappa = 100 the step takes much longer to shrink and at k=300k = 300 the cloud has not closed.

Read three properties from the figure. The plateau is proportional to η/B\eta/B, because noise per step is η2σ2/B\eta^2\sigma^2/B and contraction is ημ\eta\mu: doubling the batch and halving the step are equivalent for noise. But not for time: forgetting the start takes 1/(ημ)1/(\eta\mu) steps, so halving η\eta doubles that time, while doubling BB does not change it (but doubles the cost per step). The cloud is not round. Stationary covariance in the direction with eigenvalue λi\lambda_i is ησ2/(Bλi(2−ηλi))\eta\sigma^2/(B\lambda_i(2 - \eta\lambda_i)): proportional to 1/λi1/\lambda_i, 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 1/μ1/\mu scale of the flat direction, which takes time for large κ\kappa (change κ\kappa and see).

The practical consequence is the linear scaling rule: the plateau depends on η/B\eta/B and forgetting time on 1/(ημ)1/(\eta\mu). Multiplying BB and η\eta by cc leaves the plateau unchanged, divides steps by cc, and leaves gradient count (BB per step) unchanged: a batch cc times larger with a step cc times larger does the same in cc times fewer steps. The rule runs out when η\eta reaches the 1/L1/L stability limit or BB exceeds BnoiseB_{\text{noise}}, 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 mk=k+K0m_k = k + K_0, so ηk=2/(μmk)\eta_k = 2/(\mu m_k) and 1−μηk=(mk−2)/mk1 - \mu\eta_k = (m_k - 2)/m_k (nonnegative since mk≥K0≥2m_k \ge K_0 \ge 2). The recurrence gives ak+1≤mk−2mkak+4σ2μ2mk2a_{k+1} \le \frac{m_k - 2}{m_k}a_k + \frac{4\sigma^2}{\mu^2m_k^2}. Multiply by mk(mk−1)m_k(m_k - 1):

mk(mk−1) ak+1≤(mk−1)(mk−2) ak+4σ2μ2⋅mk−1mk.m_k(m_k - 1)\,a_{k+1} \le (m_k - 1)(m_k - 2)\,a_k + \frac{4\sigma^2}{\mu^2}\cdot\frac{m_k - 1}{m_k}.

Since mk+1=mk+1m_{k+1} = m_k + 1, the coefficient of ak+1a_{k+1} on the left is ck+1c_{k+1} with ck:=(mk−1)(mk−2)c_k := (m_k - 1)(m_k - 2), and that on the right is ckc_k. Using (mk−1)/mk≤1(m_k - 1)/m_k \le 1 leaves ck+1ak+1≤ckak+4σ2/μ2c_{k+1}a_{k+1} \le c_ka_k + 4\sigma^2/\mu^2. Summing from k=0k = 0 to T−1T - 1, cTaT≤c0a0+4Tσ2/μ2c_Ta_T \le c_0a_0 + 4T\sigma^2/\mu^2. Divide by cT=(T+K0−1)(T+K0−2)c_T = (T + K_0 - 1)(T + K_0 - 2) and use K0−1T+K0−1≤K0T+K0\frac{K_0 - 1}{T + K_0 - 1} \le \frac{K_0}{T + K_0} (and likewise with K0−2K_0 - 2) and cT≥T2c_T \ge T^2.

∎

The result has two phases. For T≲K0T \lesssim K_0 the first term dominates: the method must wait for the step to fall enough, and the start is forgotten as (κ/T)2(\kappa/T)^2. Then 4σ2/(μ2T)4\sigma^2/(\mu^2T) dominates, error falling as 1/T1/T 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 e−T/κe^{-T/\kappa} to sublinear rate 1/T1/T. The code below checks this with simulated replicas, with slope −1-1 on a log-log scale. The schedule contains μ\mu, and that matters: with ηk=c/k\eta_k = c/k on scalar quadratic F=μ2x2F = \frac\mu2x^2, ∏j(1−cμ/j)\prod_j(1 - c\mu/j) decays as k−cμk^{-c\mu}, so if 2cμ<12c\mu < 1 mean squared error falls only as k−2cμk^{-2c\mu}, much slower than 1/k1/k (Nemirovski, Juditsky, Lan and Shapiro, 2009, note this as the chief fragility of 1/k1/k steps). The theorem takes c=2/μc = 2/\mu, with 2cμ=42c\mu = 4, and the first figure c=1/μc = 1/\mu. Underestimating μ\mu worsens only the constant; overestimating it can break the rate. That 1/T1/T 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 ϵ>0\epsilon > 0, choose KK such that ηkσ2≤μϵ/2\eta_k\sigma^2 \le \mu\epsilon/2 for k≥Kk \ge K. Then ak+1≤(1−μηk)ak+ηk⋅μϵ/2a_{k+1} \le (1 - \mu\eta_k)a_k + \eta_k\cdot\mu\epsilon/2, and subtracting ϵ/2\epsilon/2 from both sides gives ak+1−ϵ/2≤(1−μηk)(ak−ϵ/2)a_{k+1} - \epsilon/2 \le (1 - \mu\eta_k)(a_k - \epsilon/2). By induction, (ak−ϵ/2)+≤∏j=Kk−1(1−μηj) (aK−ϵ/2)+≤e−μ∑j=Kk−1ηj(aK−ϵ/2)+→0(a_k - \epsilon/2)_+ \le \prod_{j=K}^{k-1}(1 - \mu\eta_j)\,(a_K - \epsilon/2)_+ \le e^{-\mu\sum_{j=K}^{k-1}\eta_j}(a_K - \epsilon/2)_+ \to 0, because the sum diverges. Thus lim sup⁡ak≤ϵ/2\limsup a_k \le \epsilon/2 for every ϵ\epsilon. Conversely, for scalar quadratic xk+1=(1−μηk)xk−ηkζkx_{k+1} = (1 - \mu\eta_k)x_k - \eta_k\zeta_k with ζk\zeta_k zero-mean and independent of xkx_k, the cross term vanishes and E[xk+12]=(1−μηk)2E[xk2]+ηk2E[ζk2]≥(1−μηk)2E[xk2]\E[x_{k+1}^2] = (1 - \mu\eta_k)^2\E[x_k^2] + \eta_k^2\E[\zeta_k^2] \ge (1 - \mu\eta_k)^2\E[x_k^2]; and, since 0<μηj<10 < \mu\eta_j < 1, ∏(1−μηj)>0\prod(1 - \mu\eta_j) > 0 if and only if ∑ηj<∞\sum\eta_j < \infty.

∎

Notice the nuance. Under strong convexity ηk→0\eta_k \to 0 and ∑ηk=∞\sum\eta_k = \infty suffice, and a 1/k1/\sqrt{k} step, violating ∑ηk2<∞\sum\eta_k^2 < \infty, converges in mean square; moreover, with ηk∝1/k\eta_k \propto 1/\sqrt{k} mean squared error falls as 1/k1/\sqrt{k}, slower than the optimal step’s 1/k1/k: this is the −1/2-1/2 slope we measure. The condition ∑ηk2<∞\sum\eta_k^2 < \infty 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 ∑ηk2<∞\sum\eta_k^2 < \infty: 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 ηk\eta_k 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 xk+1−xk=−η(Axk+εk)\vb{x}_{k+1} - \vb{x}_k = -\eta(\mat{A}\vb{x}_k + \vb{\varepsilon}_k) from k=0k = 0 to T−1T - 1 telescopes the left side, leaving xT−x0=−ηA∑kxk−η∑kεk\vb{x}_T - \vb{x}_0 = -\eta\mat{A}\sum_k\vb{x}_k - \eta\sum_k\vb{\varepsilon}_k. Solve for ∑kxk=TxˉT\sum_k\vb{x}_k = T\bar{\vb{x}}_T and multiply by A−1\mat{A}\inv. The bound follows from ∥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 independence, which gives E∥A−1∑kεk∥2=Ttr⁡(A−1ΣεA−1)\E\norm{\mat{A}\inv\sum_k\vb{\varepsilon}_k}^2 = T\tr(\mat{A}\inv\Sigma_\varepsilon\mat{A}\inv).

∎

Look at the second term. Average error has a noise part, tr⁡(A−1ΣεA−1)/T\tr(\mat{A}\inv\Sigma_\varepsilon\mat{A}\inv)/T, decaying as 1/T1/T and independent of η\eta, and a start-up part decaying as 1/(ηT)21/(\eta T)^2, much faster. Compare the last iterate, which cannot fall below the plateau ∝η\propto\eta. Two consequences. First, with averaging a constant step can be large without penalty to final variance (only η<2/λmax⁡\eta < 2/\lambda_{\max} is needed and, to forget the start quickly, not too small). Second, the constant A−1ΣεA−1\mat{A}\inv\Sigma_\varepsilon\mat{A}\inv cannot be improved: it is the covariance a maximum-likelihood estimator observing Ax⋆+ε\mat{A}\vb{x}^\star + \vb{\varepsilon} with Gaussian noise of covariance Σε\Sigma_\varepsilon would achieve (its Fisher information is AΣε−1A\mat{A}\Sigma_\varepsilon\inv\mat{A}), the Cramér–Rao limit. Polyak and Juditsky (1992) proved this remains true for nonquadratic, strongly convex, smooth FF, with steps ηk∝k−α\eta_k \propto k^{-\alpha} for α∈(1/2,1)\alpha \in (1/2, 1): T(xˉT−x⋆)\sqrt{T}(\bar{\vb{x}}_T - \vb{x}^\star) converges in distribution to a Gaussian with covariance H−1ΣH−1\mat{H}\inv\Sigma\mat{H}\inv, where H\mat{H} is the Hessian at x⋆\vb{x}^\star. The general case is not proved here.

InteractiveAveraging the noise
  • last iterate
  • full-run average
  • tail average
  • noise floor ∝ 1/k
  • last-iterate plateau
0.316
300
k = 1000
Last iterate error²0.4
Full-run average error²0.0291
Tail average error²0.0339
Last ÷ average ratio13.7
The average now beats the last iterate: its error falls as 1/k1/k with constant tr⁡(A−2Σ)\operatorname{tr}(\mathbf{A}^{-2}\Sigma) independent of step size, while the last iterate stays on its plateau.
2D quadratic with λ=(1,0.1)\lambda = (1, 0.1) and noise standard deviation 0.50.5 per coordinate, starting from (2,2)(2, 2) with constant step. Left, one replica: iterates (blue), average of the whole trajectory (magenta) and tail average from k0k_0 (violet). Right, mean squared error of all three estimates over 100 replicas, with noise floor tr⁡(A−2Σε)/k\tr(\mat{A}^{-2}\Sigma_\varepsilon)/k (dashed) and last-iterate plateau. With initial settings (η≈0.32\eta \approx 0.32, k0=300k_0 = 300), at k=1000k = 1000 the last iterate has error2^2 0.400.40, the full average 0.0290.029 and tail average 0.0340.034, against a noise floor of 0.0250.025. Move k0k_0 and η\eta: with small η\eta the average takes a long time to forget the start, and the tail average discards it and is better initially; with large η\eta the last-iterate plateau rises but the average barely notices.

Tail averaging resolves the figure’s tradeoff. Averaging the whole trajectory carries early iterates far from optimum, with bias decaying as 1/(ηT)21/(\eta T)^2. Tail averaging discards them and therefore forgets the start much sooner, at the cost of averaging fewer iterates (its noise floor is tr⁡(⋅)/(T−k0)\tr(\cdot)/(T - k_0)). The most common rule is to average the last half, or last fraction α\alpha, of iterates. Rakhlin, Shamir and Sridharan (2012) show that for nonsmooth strongly convex objectives with 1/(μk)1/(\mu k) steps, suffix averaging reaches the previous section’s O(1/T)\bigO(1/T) rate, while averaging the full trajectory can lose a factor log⁡T\log T; the last iterate also loses it in that nonsmooth case (Shamir and Zhang, 2013, gave the O(log⁡T/T)\bigO(\log T/T) 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 nn 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 i1,…,iji_1, \dots, i_j have already been seen, the next is chosen among those remaining, and E[g∣past]≠∇F(xk)\E[\vb{g} \given \text{past}] \ne \grad F(\vb{x}_k). This complicates analysis. In exchange it has a geometric advantage: if the iterate were frozen, the sum of an epoch’s nn gradients would be exactly n∇F(x)n\grad F(\vb{x}), without sampling error, whereas with replacement the sum has variance nσ2n\sigma^2. Noise cancels within the epoch. Mishchenko, Khaled and Richtárik (arXiv:2006.05988) prove this rigorously when each fif_i is strongly convex and smooth (and with worse constants when only FF is): with sufficiently small constant step η\eta, RR mean squared error at each epoch’s end stabilizes at order η3nLσ⋆2/μ\eta^3nL\sigma_\star^2/\mu, where σ⋆2\sigma_\star^2 is individual-gradient variance at optimum, versus ησ⋆2/μ\eta\sigma_\star^2/\mu 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 Eξ[f(x;ξ)]\E_\xi[f(\vb{x};\xi)] 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 n=2000n = 2000, d=10d = 10 and μ=λ=0.01\mu = \lambda = 0.01; Newton finds the minimum to provide an exact reference f⋆f^\star.

[ ]SGD with schedules and averagingBrowser
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 kk is also the number of evaluated gradients. With constant step, the last iterate stays in its noise ball: f(xk)−f⋆f(\vb{x}_k) - f^\star is 1.3⋅10−21.3 \cdot 10^{-2} at k=1000k = 1000 and 1.4⋅10−21.4 \cdot 10^{-2} at k=4000k = 4000, with no improvement, while its average keeps falling (4.5⋅10−34.5 \cdot 10^{-3} and 1.0⋅10−31.0 \cdot 10^{-3}), about 14 times better than the final last iterate. With schedule 2/(μ(k+K0))2/(\mu(k + K_0)), with K0=⌈2Lmax⁡/μ⌉=974K_0 = \lceil 2L_{\max}/\mu\rceil = 974 (calibrated to worst-example smoothness Lmax⁡L_{\max}, not LL), the last iterate reaches 2.6⋅10−32.6 \cdot 10^{-3} and the average 1.2⋅10−31.2 \cdot 10^{-3}. With ηk∝1/k\eta_k \propto 1/\sqrt{k} averaging the entire trajectory worsens the last iterate (8.5⋅10−38.5 \cdot 10^{-3} versus 3.0⋅10−33.0 \cdot 10^{-3}): 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 ∑iηsi/(λi(2−ηλi))\sum_i\eta s_i/(\lambda_i(2 - \eta\lambda_i)), and the decreasing-step theorem’s bound.

[ ]Measuring SGD ratesBrowser
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: 0.01≈00.01 \approx 0 for constant step (a plateau), −0.52≈−1/2-0.52 \approx -1/2 for 1/k1/\sqrt{k} and −1.05≈−1-1.05 \approx -1 for 2/(μ(k+K0))2/(\mu(k + K_0)). The measured plateau, 0.04190.0419, agrees with theoretical 0.04030.0403 within Monte Carlo error (a few percent with 1500 replicas). The theorem’s bound holds for every kk with slack factor 3.4 (maximum ratio 0.2950.295), and the asymptotic value of k E∥xk∥2k\,\E\norm{\vb{x}_k}^2 is 1.781.78, nine times smaller than 4σ2/μ2=164\sigma^2/\mu^2 = 16: the bound uses the worst case with all noise in the μ\mu curvature direction, while here noise is spread over five directions with curvatures from 11 to 2020.

The third cell measures noise scale in the first logistic regression. It computes gradients of all nn examples, tr⁡Σ\tr\Sigma, ∥∇F∥2\norm{\nabla F}^2 and BnoiseB_{\text{noise}} during GD training, then checks 1/(1+Bnoise/B)1/(1 + B_{\text{noise}}/B) by measuring for each batch size the expected decrease of one step using the best η\eta on a grid. Alongside the simple scale tr⁡Σ/∥∇F∥2\tr\Sigma/\norm{\nabla F}^2, it computes the curvature-weighted scale tr⁡(HΣ)/(∇F⊤H∇F)\tr(\mat{H}\Sigma)/(\nabla F\T\mat{H}\nabla F), exact for a quadratic: it follows from the theorem’s calculation using F(x−ηgˉ)=F−η∥∇∥2+η22(∇⊤H∇+tr⁡(HΣ)/B)F(\vb{x} - \eta\bar{\vb{g}}) = F - \eta\norm{\nabla}^2 + \frac{\eta^2}{2}(\nabla\T\mat{H}\nabla + \tr(\mat{H}\Sigma)/B).

[ ]Noise scale and critical batchBrowser
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, ∥∇F∥2\norm{\nabla F}^2 falls from 7.0⋅10−27.0 \cdot 10^{-2} to 2.2⋅10−62.2 \cdot 10^{-6}, while tr⁡Σ\tr\Sigma falls only from 1.031.03 to 0.650.65: simple noise scale rises from 1515 to over 3⋅1053 \cdot 10^5. 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 BB. The second table checks the law. At iteration 0, the decrease with the best step for each BB, normalized by that at B=1024B = 1024, follows 1/(1+Bnoise/B)1/(1 + B_{\text{noise}}/B): with B=16B = 16 measured 0.5590.559 versus predicted 0.5270.527 (simple) and 0.5820.582 (weighted); with B=64B = 64, 0.8060.806 versus 0.8240.824 and 0.8540.854. At iteration 5, curvature-weighted scale BH=3694B_H = 3694 reproduces data almost exactly (0.3000.300 measured versus 0.2990.299 with B=256B = 256), while simple Bnoise=987B_{\text{noise}} = 987 overestimates it (0.4040.404): 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 x⋆\vb{x}^\star to measure the noise floor directly, with 400 parallel replicas, and inspect error at the end of each epoch.

[ ]With and without replacement: the noise floorBrowser
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 2.22.2 times (nearly linearly in η\eta), and the shuffled floor by 6.66.6 times, approaching factor 23=82^3 = 8 of the η3\eta^3 law: from η=0.04\eta = 0.04 to η=0.01\eta = 0.01, SGD improves 4.54.5 times and RR 5151. At η=0.01\eta = 0.01 shuffling is 3030 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 nn, 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 needOptionNote
Step x←x−ηg\vb{x} \leftarrow \vb{x} - \eta\vb{g}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 replacementRandomSampler(dataset, replacement=True) or WeightedRandomSamplerThe analysis model; useful for differently weighted examples.
Polyak–Ruppert averagingtorch.optim.swa_utils.AveragedModelCall update_parameters(model) after each step (or epoch); the default is the arithmetic mean.
Step scheduletorch.optim.lr_scheduler.*The subject of the next lesson.

The next cell checks three exact equivalences on a tiny problem (CPU, float64).

[ ]PyTorch: step, shuffling and averagingLocal GPU
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())
This cell needs the local lab (PyTorch with your GPU). Start it with 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 10−1710^{-17}, 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

ProofStrongly convex SGD recurrence and its plateau
Prove: Let FF be μ\mu-strongly convex and LL-smooth with minimizer x⋆\vb{x}^\star, and let xk+1=xk−ηgk\vb{x}_{k+1} = \vb{x}_k - \eta\vb{g}_k with η≤1/L\eta \le 1/L, E[gk∣Fk]=∇F(xk)\E[\vb{g}_k \given \mathcal{F}_k] = \grad F(\vb{x}_k) and E[∥gk−∇F(xk)∥2∣Fk]≤σ2\E[\norm{\vb{g}_k - \grad F(\vb{x}_k)}^2 \given \mathcal{F}_k] \le \sigma^2. Prove that ak=E∥xk−x⋆∥2a_k = \E\norm{\vb{x}_k - \vb{x}^\star}^2 satisfies ak+1≤(1−ημ)ak+η2σ2a_{k+1} \le (1 - \eta\mu)a_k + \eta^2\sigma^2 and deduce ak≤(1−ημ)ka0+ησ2/μa_k \le (1 - \eta\mu)^ka_0 + \eta\sigma^2/\mu.
0
Expand ∥xk−ηgk−x⋆∥2\norm{\vb{x}_k - \eta\vb{g}_k - \vb{x}^\star}^2, take expectation conditional on Fk\mathcal{F}_k and write E[∥gk∥2∣Fk]=∥∇F(xk)∥2+E[∥gk−∇F(xk)∥2∣Fk]\E[\norm{\vb{g}_k}^2 \given \mathcal{F}_k] = \norm{\grad F(\vb{x}_k)}^2 + \E[\norm{\vb{g}_k - \grad F(\vb{x}_k)}^2 \given \mathcal{F}_k].

Step 1 of 4. After expanding and conditioning, what bound follows for E[∥xk+1−x⋆∥2∣Fk]\E[\norm{\vb{x}_{k+1} - \vb{x}^\star}^2 \given \mathcal{F}_k]?

ProofAveraged SGD for convex objectives
Prove: Let FF be convex, x⋆\vb{x}^\star a minimizer, R=∥x0−x⋆∥R = \norm{\vb{x}_0 - \vb{x}^\star}, E[gk∣Fk]∈∂F(xk)\E[\vb{g}_k \given \mathcal{F}_k] \in \partial F(\vb{x}_k) and E∥gk∥2≤G2\E\norm{\vb{g}_k}^2 \le G^2. Prove SGD with η=R/(GT)\eta = R/(G\sqrt{T}) satisfies E[F(xˉT)]−F⋆≤RG/T\E[F(\bar{\vb{x}}_T)] - F^\star \le RG/\sqrt{T}, with xˉT=1T∑k=0T−1xk\bar{\vb{x}}_T = \frac1T\sum_{k=0}^{T-1}\vb{x}_k.
0
Start from E[∥xk+1−x⋆∥2∣Fk]=∥xk−x⋆∥2−2η⟨hk,xk−x⋆⟩+η2E[∥gk∥2∣Fk]\E[\norm{\vb{x}_{k+1} - \vb{x}^\star}^2 \given \mathcal{F}_k] = \norm{\vb{x}_k - \vb{x}^\star}^2 - 2\eta\inner{\vb{h}_k}{\vb{x}_k - \vb{x}^\star} + \eta^2\E[\norm{\vb{g}_k}^2 \given \mathcal{F}_k], with hk=E[gk∣Fk]∈∂F(xk)\vb{h}_k = \E[\vb{g}_k \given \mathcal{F}_k] \in \partial F(\vb{x}_k).

Step 1 of 3. Which property of hk\vb{h}_k bounds the cross term?

NumericBatch standard deviation
One component of the per-example gradient has variance 44 at the current point. What is the standard deviation of that component in a minibatch gradient of size B=64B = 64 (sampling with replacement)?
NumericFraction of progress achieved with batch B
At one point in training, tr⁡Σ=3.2\tr\Sigma = 3.2 and ∥∇F∥2=0.04\norm{\grad F}^2 = 0.04. According to the noise-scale theorem, what fraction of the guaranteed infinite-batch decrease is achieved with B=20B = 20 and the best step?
NumericSampling a large batch without replacement
A finite sum has n=1000n = 1000 examples and total individual-gradient variance σ2=9\sigma^2 = 9. What is the total gradient variance of a batch of B=100B = 100 examples chosen without replacement?
QuizWhich steps satisfy Robbins–Monro?
The Robbins–Monro conditions require ∑ηk=∞\sum\eta_k = \infty and ∑ηk2<∞\sum\eta_k^2 < \infty. Which sequences satisfy them? (A) ηk=1/(k+1)\eta_k = 1/(k+1). (B) ηk=1/k+1\eta_k = 1/\sqrt{k+1}. (C) ηk=1/(k+1)2\eta_k = 1/(k+1)^2. (D) constant ηk=η\eta_k = \eta.
QuizHalving the step versus doubling the batch
SGD with constant step η\eta and batch BB is at its plateau. You want to halve the plateau of E∥x−x⋆∥2\E\norm{\vb{x} - \vb{x}^\star}^2, and have two choices: (i) reduce η\eta to η/2\eta/2 with the same batch, (ii) double the batch to 2B2B with the same step. For small steps, how do they differ?
CodeGeneric SGD with shuffling and averaging
Implement 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)
Shift+Enter to run

Summary

Key idea
SGD swaps an exact gradient costing nn for a noisy unbiased one costing 1: it makes more progress per gradient evaluated while required accuracy is moderate, and noise sets a floor ∝η/B\propto\eta/B removed by reducing the step or averaging iterates.
  • The objective is an expectation F(x)=Eξf(x;ξ)F(\vb{x}) = \E_\xi f(\vb{x};\xi) 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 σ2\sigma^2 exists for least squares.
  • SGD steps obey E[∥xk+1−x⋆∥2∣Fk]=∥xk−x⋆∥2−2ηk⟨∇F(xk),xk−x⋆⟩+ηk2E[∥gk∥2∣Fk]\E[\norm{\vb{x}_{k+1} - \vb{x}^\star}^2 \given \mathcal{F}_k] = \norm{\vb{x}_k - \vb{x}^\star}^2 - 2\eta_k\inner{\grad F(\vb{x}_k)}{\vb{x}_k - \vb{x}^\star} + \eta_k^2\E[\norm{\vb{g}_k}^2 \given \mathcal{F}_k]: signal of order η\eta, noise of order η2\eta^2. Robbins–Monro conditions ∑ηk=∞\sum\eta_k = \infty and ∑ηk2<∞\sum\eta_k^2 < \infty ensure enough reach and finite accumulated noise; with ηk=1/(k+1)\eta_k = 1/(k+1), SGD on the mean is the sample mean and its convergence is the law of large numbers.
  • Minibatch gradient variance is σ2/B\sigma^2/B (with replacement) or σ2Bn−Bn−1\frac{\sigma^2}{B}\frac{n-B}{n-1} (without). Noise scale Bnoise=tr⁡Σ/∥∇F∥2B_{\text{noise}} = \tr\Sigma/\norm{\grad F}^2 gives progress 1/(1+Bnoise/B)1/(1 + B_{\text{noise}}/B) per step: with B≪BnoiseB \ll B_{\text{noise}} a larger batch is nearly free, while with B≫BnoiseB \gg B_{\text{noise}} it is wasted. BnoiseB_{\text{noise}} grows during training.
  • For convex objectives, the average satisfies EF(xˉT)−F⋆≤RG/T\E F(\bar{\vb{x}}_T) - F^\star \le RG/\sqrt{T}, independent of nn and dd; with smoothness, 2LR2/T+2Rσ/T2LR^2/T + 2R\sigma/\sqrt{T}. For strongly convex objectives, recurrence ak+1≤(1−ημ)ak+η2σ2a_{k+1} \le (1 - \eta\mu)a_k + \eta^2\sigma^2 gives linear convergence to a noise ball with radius2^2 ησ2/μ\eta\sigma^2/\mu at constant step, and O(1/T)\bigO(1/T) with ηk=2/(μ(k+K0))\eta_k = 2/(\mu(k + K_0)).
  • Polyak–Ruppert averaging, leaving the step unchanged, has error tr⁡(A−1ΣA−1)/T\tr(\mat{A}\inv\Sigma\mat{A}\inv)/T independent of η\eta on a quadratic; tail averaging discards the start. Shuffled epochs (without replacement) reduce the noise floor from O(η)\bigO(\eta) to O(η3)\bigO(\eta^3) 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.