Skip to content
LeetQuant
E05 Advanced Optimisation

E05 · Advanced Optimisation · Lesson 4 of 4

Stochastic Gradient Methods

SGD convergence with constant and decaying steps, the noise floor and how it scales with step and batch size, Polyak–Ruppert averaging, momentum and Adam, and a runnable comparison on least squares.

20 min

Beyond "SGD is noisy"

The gradient-descent lesson introduced SGD, mini-batches, momentum and the Robbins–Monro conditions. This lesson quantifies them: how large the noise floor of constant-step SGD is, exactly how a 1/k1/k schedule can fail, why averaging is so effective, what momentum and Adam do and do not fix, and how to choose a batch size.

Objective: predict the noise floor from the step size, batch size and gradient variance; choose a schedule that converges at the optimal rate; explain Adam's update and bias correction; and run a fair comparison.

Setup

Minimise f(x)=1n∑ifi(x)f(x) = \tfrac1n\sum_i f_i(x), mm-strongly convex and LL-smooth, using a stochastic gradient gkg_k with

E[gk∣xk]=∇f(xk),Cov⁡(gk∣xk)=Q(xk)/B,\mathbb E[g_k \mid x_k] = \nabla f(x_k), \qquad \operatorname{Cov}(g_k \mid x_k) = Q(x_k)/B,

where QQ is the covariance of a single-example gradient and BB the batch size (sampling with replacement; without replacement from nn examples multiply by (n−B)/(n−1)(n - B)/(n - 1)). The key point: at the optimum ∇f(x∗)=0\nabla f(x^*) = 0 but Q(x∗)≠0Q(x^*) \ne 0, because individual ∇fi(x∗)\nabla f_i(x^*) do not vanish.

Constant step: linear convergence to a noise floor

Near x∗x^*, write dk=xk−x∗d_k = x_k - x^* and H=∇2f(x∗)H = \nabla^2 f(x^*). The update is dk+1=(I−ηH)dk−ηξkd_{k+1} = (I - \eta H)d_k - \eta\xi_k with noise covariance Q/BQ/B. The mean of dkd_k shrinks like (I−ηH)k(I - \eta H)^k, at the deterministic rate. The covariance PP settles where P=(I−ηH)P(I−ηH)+η2Q/BP = (I - \eta H)P(I - \eta H) + \eta^2 Q/B, which for small η\eta is

HP+PH≈ηBQ.HP + PH \approx \frac{\eta}{B}Q .

For least squares with homoscedastic noise of variance σ2\sigma^2, the per-example gradient at the optimum is −xiεi-x_i\varepsilon_i, so Q=σ2HQ = \sigma^2 H and the solution is P=ησ22BIP = \tfrac{\eta\sigma^2}{2B}I. The expected excess loss is 12tr⁡(HP)\tfrac12\operatorname{tr}(HP):

E[f(xk)]−f∗ ⟶ η σ2tr⁡(H)4B.\mathbb E[f(x_k)] - f^* \ \longrightarrow\ \frac{\eta\,\sigma^2\operatorname{tr}(H)}{4B} .

The floor is proportional to η/B\eta/B: halve the step or double the batch and it halves. Its scale is set by the noise and the total curvature, not by the condition number. For general strongly convex problems the same structure holds up to constants: error ≲(1−ηm)k⋅initial+O(η σg2/(mB))\lesssim (1 - \eta m)^k \cdot \text{initial} + O(\eta\,\sigma_g^2/(mB)), with σg2\sigma_g^2 the gradient variance at the optimum.

Decaying steps, and how 1/k1/k can fail

To get past the floor, η\eta must go to zero, but slowly enough to keep moving: ∑kηk=∞\sum_k\eta_k = \infty and ∑kηk2<∞\sum_k\eta_k^2 < \infty. The standard schedule is ηk=c/(k+k0)\eta_k = c/(k + k_0), which for strongly convex ff gives E∥xk−x∗∥2=O(1/k)\mathbb E\|x_k - x^*\|^2 = O(1/k), provided c>1/(2m)c > 1/(2m). If cc is too small the method is far slower than 1/k1/k: on f=m2x2f = \tfrac m2 x^2 the deterministic part of the error after kk steps is

∏j=1k(1−cmj)≈k−cmΓ(1−cm),\prod_{j=1}^k\Big(1 - \frac{cm}{j}\Big) \approx \frac{k^{-cm}}{\Gamma(1 - cm)},

so the squared error decays like k−2cmk^{-2cm}, and with cm<12cm < \tfrac12 the noise term also decays slower than 1/k1/k. Underestimating the curvature is therefore costly, and mm is rarely known. Two practical consequences:

  • Constant then decay. Run a constant step while far away (fast linear progress), then decay once the loss plateaus ("step decay", or 1/k1/k with a large offset k0k_0).
  • Polyak–Ruppert averaging. Run a larger step, ηk∝k−α\eta_k \propto k^{-\alpha} with α∈(12,1)\alpha \in (\tfrac12, 1) or even constant for least squares, and report the average xˉk=1k∑j≤kxj\bar x_k = \tfrac1k\sum_{j \le k}x_j. The average achieves the asymptotically optimal covariance 1kH−1QH−1\tfrac1k H^{-1}QH^{-1}, the same as the best possible estimator from kk samples (the sandwich covariance of M-estimation), without knowing mm. Averaging cancels the oscillation around x∗x^*; it lags when the iterates are still drifting, which is why one averages only the tail.

For convex but not strongly convex problems, ηk∝1/k\eta_k \propto 1/\sqrt k with averaging gives Ef(xˉk)−f∗=O(1/k)\mathbb E f(\bar x_k) - f^* = O(1/\sqrt k), which is optimal for that class.

Mini-batch size

A batch of BB costs BB example-gradients and cuts the variance by BB. Two regimes:

  • Noise-dominated (small BB): doubling BB and doubling η\eta keeps η/B\eta/B and the floor fixed while halving the number of steps per epoch, so progress per example is unchanged and wall-clock time falls on parallel hardware. This is the "linear scaling rule".
  • Curvature-dominated (large BB): the step is capped by stability, η<2/L\eta < 2/L, whatever the batch. Past that point, larger batches cost more examples for the same progress.

The crossover is roughly the gradient noise scale Bcrit≈tr⁡(Q)/∥∇f∥2B_{\text{crit}} \approx \operatorname{tr}(Q)/\|\nabla f\|^2: the batch at which the noise in the gradient is comparable to its signal. It grows as training approaches the optimum (the signal shrinks), which is one argument for increasing the batch size over training instead of decaying the step.

Worked example

a step size that is too timid

Minimise f(x)=0.05x2f(x) = 0.05x^2 (so m=0.1m = 0.1) from x0=1x_0 = 1, ignoring noise, with ηk=c/k\eta_k = c/k. How far has xx moved after 10610^6 steps for c=1c = 1 and for c=5c = 5? What about c=10c = 10?

Show solution

Each step multiplies xx by 1−ηkm=1−cm/k1 - \eta_k m = 1 - cm/k.

  • c=1c = 1 (cm=0.1cm = 0.1): ∏k≤106(1−0.1/k)=0.235\prod_{k \le 10^6}(1 - 0.1/k) = 0.235, against the approximation 10−0.6/Γ(0.9)=0.251/1.069=0.23510^{-0.6}/\Gamma(0.9) = 0.251/1.069 = 0.235. A million steps remove only three-quarters of the initial error.
  • c=5c = 5 (cm=0.5cm = 0.5): the product is 5.6×10−45.6 \times 10^{-4} (approximation 10−3/Γ(0.5)=10−3/1.77210^{-3}/\Gamma(0.5) = 10^{-3}/1.772).
  • c=10c = 10 (cm=1cm = 1): the first factor is 1−1=01 - 1 = 0, so the first step lands exactly on the optimum. (With noise, c=1/mc = 1/m makes xkx_k the running average of the noisy targets, the optimal estimator; this is the "SGD for a mean" example from the gradient-descent lesson.)

The rule c>1/(2m)c > 1/(2m) is not a technicality: a schedule scaled for the wrong curvature can look converged while it is stuck.

Momentum and Adam with noisy gradients

Momentum vk+1=βvk+gkv_{k+1} = \beta v_k + g_k, xk+1=xk−ηvk+1x_{k+1} = x_k - \eta v_{k+1} accumulates gradients with weights summing to 1/(1−β)1/(1 - \beta), so in a steady regime it behaves like SGD with effective step η/(1−β)\eta/(1 - \beta). Its benefit, the κ\sqrt\kappa acceleration, is about the deterministic bias term. It does not reduce the noise floor at a given effective step: the noise is averaged over about 1/(1−β)1/(1 - \beta) steps but each step is 1/(1−β)1/(1 - \beta) times larger. Accelerated methods are also known to amplify gradient noise, so in the noise-dominated phase momentum mostly helps by smoothing direction, and its gain over tuned SGD is modest.

Adam keeps exponential averages of the gradient and of its elementwise square, corrects their start-up bias, and divides:

mt=β1mt−1+(1−β1)gt,st=β2st−1+(1−β2)gt2,xt=xt−1−η mt/(1−β1t)st/(1−β2t)+ϵ,m_t = \beta_1 m_{t-1} + (1 - \beta_1)g_t, \quad s_t = \beta_2 s_{t-1} + (1 - \beta_2)g_t^2, \quad x_t = x_{t-1} - \eta\,\frac{m_t/(1 - \beta_1^t)}{\sqrt{s_t/(1 - \beta_2^t)} + \epsilon},

with defaults β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999, ϵ=10−8\epsilon = 10^{-8}.

  • Bias correction. With m0=0m_0 = 0 and a stationary gradient distribution, E[mt]=(1−β1t)E[g]\mathbb E[m_t] = (1 - \beta_1^t)\mathbb E[g]; dividing by 1−β1t1 - \beta_1^t removes the shrinkage towards zero in early steps, and likewise for sts_t.
  • Scale invariance. Multiplying the loss by a constant leaves the update unchanged (apart from ϵ\epsilon). Each coordinate moves by roughly η\eta times a signal-to-noise ratio Eg/Eg2∈[−1,1]\mathbb E g/\sqrt{\mathbb E g^2} \in [-1, 1], so η\eta is a step in parameter units and coordinates with tiny gradients (badly scaled features) are not starved. This diagonal preconditioning is the main reason Adam is robust to scaling.
  • Limitations. Adam is not guaranteed to converge even on convex problems with fixed hyperparameters (the AMSGrad counterexamples), it still needs a decaying η\eta to reach the optimum, and L2 regularisation inside Adam is not weight decay (use AdamW). On well-conditioned convex problems, tuned SGD with averaging is usually as good.

Worked example

Adam's first step

At t=1t = 1 a parameter has gradient g1g_1 (any nonzero value). With the default β1,β2\beta_1, \beta_2 and negligible ϵ\epsilon, what is Adam's first step, with and without bias correction?

Show solution

m1=(1−β1)g1=0.1g1m_1 = (1 - \beta_1)g_1 = 0.1g_1 and s1=(1−β2)g12=0.001g12s_1 = (1 - \beta_2)g_1^2 = 0.001g_1^2.

With correction: m^1=m1/0.1=g1\hat m_1 = m_1/0.1 = g_1 and s^1=s1/0.001=g12\hat s_1 = s_1/0.001 = g_1^2, so the step is η g1/∣g1∣=ηsign⁡(g1)\eta\,g_1/|g_1| = \eta\operatorname{sign}(g_1). Every coordinate moves by exactly η\eta on the first step, whatever its gradient's scale: a gradient of 100100 and one of 0.010.01 produce the same move.

Without correction: m1/s1=0.1g1/(0.001 ∣g1∣)=3.16sign⁡(g1)m_1/\sqrt{s_1} = 0.1g_1/(\sqrt{0.001}\,|g_1|) = 3.16\operatorname{sign}(g_1), a first step 3.163.16 times too large. Because β2\beta_2 is much closer to 1 than β1\beta_1, the uncorrected denominator is far more biased towards zero than the numerator, and early steps overshoot. The ratio decays to 1 only over roughly 1/(1−β2)=1,0001/(1 - \beta_2) = 1{,}000 steps.

A runnable comparison on least squares

Ten features with scales from 1 down to 0.1 (κ≈100\kappa \approx 100), n=5,000n = 5{,}000, noise σ=0.5\sigma = 0.5. Every method gets the same budget: 20 passes' worth of single-example gradients. "Iterate" is the typical excess loss of the iterate over the last 5% of steps (the noise floor); "averaged" is the excess loss of the Polyak–Ruppert average of the second half.

import numpy as np

rng = np.random.default_rng(0)
n, p, sigma = 5_000, 10, 0.5
X = rng.standard_normal((n, p)) * np.logspace(0, -1, p)   # feature scales 1 ... 0.1
y = X @ rng.standard_normal(p) + sigma * rng.standard_normal(n)

H = X.T @ X / n                                  # Hessian of f(b) = |y - Xb|^2 / 2n
beta_hat = np.linalg.solve(H, X.T @ y / n)
def excess(b):                                   # f(b) - f(beta_hat), exact for a quadratic
    d = b - beta_hat
    return 0.5 * d @ H @ d
eig = np.linalg.eigvalsh(H)
print(f"L = {eig[-1]:.3f}, m = {eig[0]:.4f}, kappa = {eig[-1] / eig[0]:.0f}, tr H = {eig.sum():.3f}")

def run(method, batch, lr, epochs=20, seed=1):
    """Same budget for every method: 20 passes' worth of per-example gradients."""
    rng = np.random.default_rng(seed)
    b, v, s, avg = np.zeros(p), np.zeros(p), np.zeros(p), np.zeros(p)
    steps = epochs * n // batch
    late = []
    for t in range(1, steps + 1):
        j = np.arange(n) if batch == n else rng.integers(0, n, batch)
        g = X[j].T @ (X[j] @ b - y[j]) / batch   # unbiased estimate of the full gradient
        if method == "sgd":
            b -= lr * g
        elif method == "sgd 1/k":
            b -= lr / (1 + t / 5_000) * g        # eta_k ~ 1/k in the tail
        elif method == "momentum":
            v = 0.9 * v + g
            b -= lr * v
        elif method == "adam":
            v = 0.9 * v + 0.1 * g
            s = 0.999 * s + 0.001 * g * g
            b -= lr * (v / (1 - 0.9**t)) / (np.sqrt(s / (1 - 0.999**t)) + 1e-8)
        if t > steps // 2:                       # Polyak-Ruppert average of the second half
            avg += (b - avg) / (t - steps // 2)
        if t > steps - steps // 20:              # typical excess over the last 5% of steps
            late.append(excess(b))
    return np.mean(late), excess(avg)

runs = [("gd", n, 1.0), ("sgd", 1, 0.05), ("sgd", 1, 0.2), ("sgd 1/k", 1, 0.2),
        ("sgd", 32, 0.5), ("momentum", 32, 0.05), ("adam", 32, 0.01)]
for method, batch, lr in runs:
    last, averaged = run("sgd" if method == "gd" else method, batch, lr)
    print(f"{method:<9} B={batch:<5} lr={lr:<5} iterate {last:.1e}   averaged {averaged:.1e}")
L = 1.006, m = 0.0101, kappa = 99, tr H = 2.487
gd        B=5000  lr=1.0   iterate 4.4e-03   averaged 6.6e-03
sgd       B=1     lr=0.05  iterate 9.3e-03   averaged 2.4e-05
sgd       B=1     lr=0.2   iterate 5.2e-02   averaged 3.2e-05
sgd 1/k   B=1     lr=0.2   iterate 1.6e-03   averaged 2.1e-05
sgd       B=32    lr=0.5   iterate 3.3e-03   averaged 2.2e-05
momentum  B=32    lr=0.05  iterate 2.4e-03   averaged 1.9e-05
adam      B=32    lr=0.01  iterate 8.1e-04   averaged 1.8e-05

Reading the table:

  • Full-batch GD gets only 20 steps for the same budget; with κ≈100\kappa \approx 100 the slow directions have barely moved (0.9920≈0.820.99^{20} \approx 0.82 of their error remains), and averaging its iterates only adds lag.
  • Noise floor matches theory. The formula ησ2tr⁡(H)/(4B)\eta\sigma^2\operatorname{tr}(H)/(4B) predicts 0.05×0.25×2.487/4≈7.8×10−30.05 \times 0.25 \times 2.487/4 \approx 7.8 \times 10^{-3} for η=0.05\eta = 0.05, B=1B = 1 (observed 9.3×10−39.3 \times 10^{-3}) and 2.4×10−32.4 \times 10^{-3} for η=0.5\eta = 0.5, B=32B = 32 (observed 3.3×10−33.3 \times 10^{-3}). Quadrupling η\eta at B=1B = 1 multiplies the floor by about 5.6, a little more than 4 because the small-step approximation is starting to strain (some single examples have η∥xi∥2>2\eta\|x_i\|^2 > 2).
  • Decay helps the last iterate (1.6×10−31.6 \times 10^{-3} versus 5.2×10−25.2 \times 10^{-2} from the same start), but averaging dominates everything: every stochastic method's average lands near 2×10−52 \times 10^{-5}, one to three orders of magnitude below its own iterates.
  • Momentum with η=0.05\eta = 0.05, β=0.9\beta = 0.9 has effective step 0.50.5, the same as the B=32B = 32, η=0.5\eta = 0.5 SGD run, and lands on essentially the same floor (the formula gives 2.4×10−32.4 \times 10^{-3} for both).
  • Adam's low floor here comes from its small η\eta and per-coordinate scaling of the badly scaled features, not from any reduction in gradient noise. With equal care in tuning and averaging, the methods end up close: the gradient noise, not the optimiser, sets the limit.

Knowledge check

Which step-size schedule satisfies both Robbins–Monro conditions (sum of steps infinite, sum of squared steps finite)?

Knowledge check

Constant-step SGD on least squares sits at an excess-loss noise floor of 0.004 with learning rate 0.1 and batch size 8. Roughly what floor do you expect with learning rate 0.2 and batch size 32 (assuming both are in the stable, small-step regime)?

Knowledge check

A parameter's first gradient is 0.003 and another's is 250. With Adam (bias-corrected, default betas, tiny epsilon) and learning rate 0.001, how large are their first updates?

Knowledge check

You switch from SGD with learning rate 0.5 to heavy-ball momentum with β = 0.9 and learning rate 0.05, same batch size. What happens to the noise floor in the noise-dominated regime?

Key takeaways

  • Constant-step SGD converges linearly to a noise floor; for least squares the floor is ησ2tr⁡(H)/(4B)\eta\sigma^2\operatorname{tr}(H)/(4B), proportional to step over batch size.
  • ηk=c/(k+k0)\eta_k = c/(k + k_0) gives O(1/k)O(1/k) only if c>1/(2m)c > 1/(2m); too small a cc gives k−2cmk^{-2cm}. Polyak–Ruppert averaging of a larger-step run reaches the optimal H−1QH−1/kH^{-1}QH^{-1}/k covariance without knowing mm.
  • Mini-batches: scale the step with the batch while noise dominates; beyond the gradient noise scale, the curvature limit η<2/L\eta < 2/L binds and larger batches waste examples.
  • Momentum's gain is in the bias term; at equal effective step η/(1−β)\eta/(1 - \beta) it has the same noise floor. Adam is a bias-corrected, per-coordinate normalised step of size about η\eta, robust to scaling but still needing decay and not guaranteed to converge.

Practice problems

Finished reading?

Answer the 4 knowledge checks to complete this lesson (0 done).