Course contents 07 / 27

07 / 27 · Linear Regression

Stochastic and adaptive optimizers

Gradient descent with gradients estimated from small random samples: why a minibatch gradient is unbiased and how its noise shrinks with the batch, why a constant step stalls in a noise ball when the gradient noise persists at the minimum and decreasing steps do not, momentum and Nesterov's method against the condition number, the per-coordinate steps of AdaGrad, RMSProp and Adam with Adam's bias correction, and what each of them can and cannot fix.

On this page 6

The gradient descent note ended with two costs. Every step reads all nn examples, and the number of steps grows with the condition number κ\kappa. This note attacks both. The first cost goes away when the gradient is estimated from a small random sample of examples: the steps become cheap and noisy, and the noise changes how the step size must behave. The second is reduced by remembering past gradients (momentum) and by giving each coordinate its own step size (AdaGrad, RMSProp, Adam). Adam trains almost every neural network in the Deep Learning, NLP and Generative Models courses, so it is worth knowing exactly what each of its lines does.

Notation. The loss is an average over examples, Q(w)=1n∑i=1nℓi(w)Q(w) = \frac1n\sum_{i=1}^n \ell_i(w), where ℓi\ell_i is the loss on example ii; for least squares ℓi(w)=12(⟨w,xi⟩−yi)2\ell_i(w) = \frac12(\langle w, x_i\rangle - y_i)^2 in this note. A minibatch SS is a random set of BB indices, g=1B∑i∈S∇ℓi(w)g = \frac1B\sum_{i \in S}\nabla\ell_i(w) is the stochastic gradient, and one epoch is ⌈n/B⌉\lceil n/B\rceil steps, one pass over the data. ηk\eta_k is the step size at step kk, β\beta the momentum coefficient, and mm, vv running averages of gradients and squared gradients. Products and squares of vectors in the adaptive methods are taken coordinate by coordinate. HH, μ\mu, LL and κ\kappa are the Hessian, its extreme eigenvalues and their ratio, as before.

A gradient from a sample#

The gradient of an average is the average of the gradients, ∇Q(w)=1n∑i∇ℓi(w)\nabla Q(w) = \frac1n\sum_i\nabla\ell_i(w). Pick one index ii uniformly at random: then E[∇ℓi(w)]=∇Q(w)E[\nabla\ell_i(w)] = \nabla Q(w), so a single example’s gradient is an unbiased estimate of the full one. Averaging BB independently drawn examples keeps the mean and divides the covariance by BB:

E[g]=∇Q(w),Cov⁡(g)=1B Σ(w),Σ(w)=1n∑i=1n(∇ℓi(w)−∇Q(w))(∇ℓi(w)−∇Q(w))⊤.\begin{aligned} E[g] &= \nabla Q(w), \\ \operatorname{Cov}(g) &= \frac1B\,\Sigma(w), \\ \Sigma(w) &= \frac1n\sum_{i=1}^n \big(\nabla\ell_i(w) - \nabla Q(w)\big)\big(\nabla\ell_i(w) - \nabla Q(w)\big)^\top . \end{aligned}

This is the Monte Carlo estimate of an average, and its error falls like 1/B1/\sqrt B. Stochastic gradient descent (SGD) takes the step w←w−ηgw \leftarrow w - \eta g with that estimate. A step costs O(Bd)O(Bd) instead of O(nd)O(nd). In practice the examples are shuffled once per epoch and taken in consecutive batches, sampling without replacement. At a fixed weight vector its batch covariance is smaller by the finite-population factor (n−B)/(n−1)(n-B)/(n-1). Across an epoch, batches and current weights become dependent, so the IID proof above does not apply unchanged.

We use a newly specified synthetic sensor fixture, not observations from people or equipment. Generate 240 independent rows from eight standard-normal draws z1,…,z8z_1,\ldots,z_8. Set x1=z1x_1=z_1, x2=z1+0.08z2x_2=z_1+0.08z_2 and xj=zjx_j=z_j for j=3,…,8j=3,\ldots,8. The target is y=20+4x1+4x2−3x3+2x4+4εy=20+4x_1+4x_2-3x_3+2x_4+4\varepsilon, with independent ε∼N(0,1)\varepsilon\sim N(0,1). The columns are sensor_a, sensor_b, control, ambient and four auxiliary signals. The redundant pair tests coefficient stability; the last four columns carry no true signal. Seed 20261113 fixes this teaching experiment. The data generator and new calculations were composed for this course with Codex assistance; no external dataset or benchmark scores are inputs.

Standardize all eight inputs and centre the target for this fixed optimization problem. At w=0w=0, sample 6000 batches independently with replacement, using seed 20261114. For B=1,8,64B=1,8,64, the measured gradient RMSE is 28.99,10.05,3.5428.99,10.05,3.54; tr⁡Σ/B\sqrt{\operatorname{tr}\Sigma/B} predicts 28.47,10.07,3.5628.47,10.07,3.56. The sample estimates fluctuate around the exact finite-dataset variance. Increasing the batch size eightfold reduces the theoretical error by 8\sqrt 8.

Why accept noise at all? Because early in training the full gradient is overkill: a sample of a few hundred examples already points in roughly the right direction, and one epoch of SGD takes n/Bn/B steps for the price of one full step. Nor is there a reason to optimize the training loss far more precisely than the training data determine the true minimizer; the statistical error of w^\hat w is already of order 1/n1/\sqrt n (Goodfellow, Bengio and Courville, 2016, section 8.1.3).

A constant step stalls in a noise ball#

One dimension. Take Q(w)=λ2w2Q(w) = \frac\lambda2 w^2 and a stochastic gradient λw+ξ\lambda w + \xi with independent noise ξ\xi of mean 0 and variance s2s^2. The update is wk+1=(1−ηλ)wk−ηξkw_{k+1} = (1 - \eta\lambda)w_k - \eta\xi_k. If 0<ηλ<20 < \eta\lambda < 2, the variance Vk=Var⁡(wk)V_k = \operatorname{Var}(w_k) obeys Vk+1=(1−ηλ)2Vk+η2s2V_{k+1} = (1 - \eta\lambda)^2 V_k + \eta^2 s^2 and converges to the fixed point

V∞=η2s21−(1−ηλ)2=ηs2λ(2−ηλ)≈ηs22λ(ηλ≪1).V_\infty = \frac{\eta^2 s^2}{1 - (1 - \eta\lambda)^2} = \frac{\eta s^2}{\lambda(2 - \eta\lambda)} \approx \frac{\eta s^2}{2\lambda} \quad (\eta\lambda \ll 1) .

The expected excess loss λ2V∞\frac\lambda2 V_\infty is about ηs2/4\eta s^2/4: proportional to the step. With λ=s=1\lambda = s = 1, V∞=0.1/1.9=0.0526V_\infty = 0.1/1.9 = 0.0526 for η=0.1\eta = 0.1 and 0.01/1.99=0.00500.01/1.99 = 0.0050 for η=0.01\eta = 0.01; 20,000 simulated runs give 0.0530.053 and 0.0050.005 (the Code section). A ten times smaller step gives a ten times smaller variance, a ball about 10≈3.2\sqrt{10} \approx 3.2 times narrower, but approaches it ten times more slowly, since the mean shrinks by 1−ηλ1 - \eta\lambda per step.

Least squares. Near the minimum the noise of a single example’s gradient xi(⟨w,xi⟩−yi)x_i(\langle w, x_i\rangle - y_i) comes mainly from the residual noise: its covariance is about σ2H\sigma^2 H when the residuals have variance σ2\sigma^2 and are independent of xx. Applying the one-dimensional result to each eigendirection, where the noise variance is σ2λi\sigma^2\lambda_i, gives the excess loss ∑iησ2λi/4=ησ2tr⁡(H)/4\sum_i \eta\sigma^2\lambda_i/4 = \eta\sigma^2\operatorname{tr}(H)/4 for small steps.

Figure

Expected loss under three step schedules

Exact expected-loss recurrence for SGDTwo constant-step curves plateau; the green decreasing-step curve keeps falling. The vertical axis is logarithmic.10.10.010.001060120180240constant 0.12constant 0.0250.12 / (1 + k/30)Exact expected-loss recurrence for SGDTwo constant-step curves plateau; the green decreasing-step curve keeps falling. The vertical axis is logarithmic.10.10.010.001060120180240constant 0.12constant 0.0250.12 / (1 + k/30)
Exact mean/variance recurrence for Q(w) = w²/2 with independent gradient noise: after 240 steps, losses are 0.03191, 0.00634, 0.00390. Reducing the step lowers the noise floor and slows removal of the initial bias. These are expectations, not random trajectories.

The figure isolates initial bias and gradient noise in one dimension. It propagates E[wk]E[w_k] and Var⁡(wk)\operatorname{Var}(w_k) exactly from w0=2w_0=2, with gradient noise variance 1. The expected loss is (E[wk]2+Var⁡(wk))/2(E[w_k]^2+\operatorname{Var}(w_k))/2. Constant steps leave a nonzero limit; a decreasing step continues to lower it. This expectation calculation does not claim that every sampled path decreases. The classical step conditions of Robbins and Monro (1951) are

∑kηk=∞,∑kηk2<∞:\begin{aligned} \sum_{k} \eta_k &= \infty, \\ \sum_{k} \eta_k^2 &< \infty : \end{aligned}

the steps must add up to an infinite distance, so that any starting point can be left behind, while the accumulated noise, whose variance adds up as ∑ηk2s2\sum\eta_k^2 s^2, stays finite. Steps ηk∝1/k\eta_k \propto 1/k satisfy both. For a μ\mu-strongly convex loss with bounded stochastic gradients, ηk=2/(μ(k+1))\eta_k = 2/(\mu(k + 1)) makes a weighted average of the iterates converge at the rate O(1/k)O(1/k) (Bubeck, 2015, Theorem 6.2), much slower than the linear rate of exact gradient descent: the price of the noise.

A finite run needs a concrete schedule rather than only an asymptotic condition. On the new fixture, start all weights at zero; train for 40 epochs in shuffled batches of 24, with five permutation seeds 400–404 shared across methods. The minimum training loss is 8.4568.456, and κ=568.9\kappa=568.9. SGD at η=0.15\eta=0.15 ends with mean excess loss 0.1160.116; reducing the step tenfold after 20 epochs gives 0.0290.029. With η=0.03\eta=0.03, the corresponding values are 0.0350.035 and 0.0350.035: an earlier reduction does not automatically help when progress in a flat direction is still slow. These are training-loss comparisons for the stated budget, not test performance or a general ranking of optimizers.

Averaging the iterates also shrinks the ball without touching the step. Polyak averaging reports wˉk=1k∑j≤kwj\bar w_k = \frac1k\sum_{j \le k} w_j instead of the last iterate; the exponential moving average of the weights used to train diffusion models is its modern form (DDPM training in practice).

Momentum: remember the direction#

The zigzag of the previous note had a simple cause: along the steep direction the gradient flips sign at every step, along the flat one it keeps pointing the same way, but with a small magnitude. Averaging recent gradients cancels the first and accumulates the second. Momentum, or the heavy-ball method (Polyak, 1964), keeps a velocity vv:

vk+1=βvk+∇Q(wk),wk+1=wk−η vk+1.\begin{aligned} v_{k+1} &= \beta v_k + \nabla Q(w_k), \\ w_{k+1} &= w_k - \eta\, v_{k+1} . \end{aligned}

Unrolled, vk+1=∑j≥0βj∇Q(wk−j)v_{k+1} = \sum_{j \ge 0}\beta^j\nabla Q(w_{k-j}), an exponentially weighted sum of past gradients. When the gradient is constant, the velocity grows to ∇Q/(1−β)\nabla Q/(1 - \beta), so with β=0.9\beta = 0.9 the effective step along a consistent direction is ten times η\eta; components that alternate in sign largely cancel.

On a quadratic the method can be analysed exactly like gradient descent, now as a two-term recursion per eigendirection (Goh, 2017). With the best choice η=4/(L+μ)2\eta = 4/(\sqrt L + \sqrt\mu)^2 and β=((κ−1)/(κ+1))2\beta = \big((\sqrt\kappa - 1)/(\sqrt\kappa + 1)\big)^2, the error shrinks asymptotically, per step, by

κ−1κ+1instead ofκ−1κ+1:\frac{\sqrt\kappa - 1}{\sqrt\kappa + 1} \quad \text{instead of} \quad \frac{\kappa - 1}{\kappa + 1} :

the number of steps grows like κ\sqrt\kappa instead of κ\kappa. For κ=100\kappa = 100 the factors are 0.8180.818 and 0.9800.980. The momentum factor is the spectral radius of the two-term recursion: it sets the rate over many steps, not a contraction at every step. Unlike gradient descent, the heavy ball can first move away from the minimum: from the starting point of the figure below, its error norm grows from 2.882.88 to 8.988.98 in four steps before it falls. On the quadratic of the figure below, with eigenvalues 4.54.5 and 0.0450.045, a thousandfold reduction of the loss takes gradient descent 173 steps at its best constant step and the optimally tuned heavy ball 39.

Nesterov’s method evaluates the gradient at the point the velocity is about to carry the iterate to, vk+1=βvk+∇Q(wk−ηβvk)v_{k+1} = \beta v_k + \nabla Q(w_k - \eta\beta v_k), in the form of Sutskever et al. (2013). The look-ahead corrects the velocity before it overshoots. With η=1/L\eta = 1/L and β=(κ−1)/(κ+1)\beta = (\sqrt\kappa - 1)/(\sqrt\kappa + 1) it needs 17 steps on the same problem, and unlike the heavy ball it keeps the κ\sqrt\kappa rate on every smooth strongly convex function, not only on quadratics (Bubeck, 2015, Theorem 3.18). This scaling is optimal in the first-order black-box setting: Theorem 3.15 gives a lower bound proportional to ((κ−1)/(κ+1))2(k−1)((\sqrt\kappa-1)/(\sqrt\kappa+1))^{2(k-1)} times μ∥w1−w∗∥2/2\mu\lVert w_1-w^*\rVert^2/2 for a worst-case quadratic in a Hilbert space. This is a worst-case loss bound, not a claim that every example needs that many steps.

The optimal quadratic parameters need μ\mu and LL. With stochastic gradients, the effective step η/(1−β)\eta/(1-\beta) is useful intuition for a sustained direction, not an exact universal formula for the stationary noise. On the new fixture, momentum β=0.9\beta=0.9, η=0.015\eta=0.015 reaches mean excess loss 0.0540.054 after the same 40 epochs; the halfway cut gives 0.0300.030. Learning rate, momentum and schedule must be considered together.

Per-coordinate steps: AdaGrad and RMSProp#

Momentum treats all coordinates alike. Features on different scales, or rare features that appear in few examples, call for different step sizes per coordinate, which is what standardization achieved in the gradient descent note by changing the features. Adaptive methods achieve it by changing the steps, using the gradients seen so far.

AdaGrad (Duchi, Hazan and Singer, 2011) divides each coordinate’s step by the root of the sum of its squared gradients:

Gk=Gk−1+gk2,wk+1=wk−ηGk+ε gk.\begin{aligned} G_{k} &= G_{k-1} + g_k^2, \\ w_{k+1} &= w_k - \frac{\eta}{\sqrt{G_k} + \varepsilon}\, g_k . \end{aligned}

A coordinate that has seen large gradients gets small steps; a coordinate of a rare feature, whose gradient is mostly zero, keeps a large step for the few examples where it appears. This suits sparse problems: GloVe word vectors are trained with AdaGrad (GloVe). The weakness is that GkG_k only grows, so all steps shrink towards zero even when the loss surface stops changing.

RMSProp (Hinton, Srivastava and Swersky, 2012, lecture 6e) replaces the sum by an exponential moving average, vk=ρvk−1+(1−ρ)gk2v_k = \rho v_{k-1} + (1 - \rho)g_k^2 with ρ=0.9\rho = 0.9, and divides by vk\sqrt{v_k}: the step adapts to the recent size of the gradient instead of its whole history.

Adam#

Adam (Kingma and Ba, 2015, Algorithm 1) keeps two moving averages and steps by their ratio:

mk=β1mk−1+(1−β1) gk,m^k=mk/(1−β1k),vk=β2vk−1+(1−β2) gk2,v^k=vk/(1−β2k),wk=wk−1−η m^k/(v^k+ε),\begin{aligned} m_k &= \beta_1 m_{k-1} + (1 - \beta_1)\, g_k, & \hat m_k &= m_k / (1 - \beta_1^k), \\ v_k &= \beta_2 v_{k-1} + (1 - \beta_2)\, g_k^2, & \hat v_k &= v_k / (1 - \beta_2^k), \\ w_{k} &= w_{k-1} - \eta\, \hat m_k / \big(\sqrt{\hat v_k} + \varepsilon\big), & & \end{aligned}

with m0=v0=0m_0 = v_0 = 0 and the defaults η=10−3\eta = 10^{-3}, β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999, ε=10−8\varepsilon = 10^{-8}.

Where the bias correction comes from (Kingma and Ba, 2015, section 3). Unrolling the recursion, mk=(1−β1)∑i=1kβ1k−igim_k = (1 - \beta_1)\sum_{i=1}^k \beta_1^{k-i} g_i. If the gradients have a constant mean E[g]E[g], then E[mk]=(1−β1)∑i=1kβ1k−i E[g]=(1−β1k) E[g]E[m_k] = (1 - \beta_1)\sum_{i=1}^k\beta_1^{k-i}\,E[g] = (1 - \beta_1^k)\,E[g], by the geometric sum. The average started at zero underestimates the mean by the factor 1−β1k1 - \beta_1^k, which is 0.10.1 at the first step, and dividing by it removes the bias; the same holds for vkv_k with β2\beta_2. Ignoring ε\varepsilon, without the correction the first step would be η⋅0.1 g/0.001 g2=3.16 η\eta\cdot 0.1\,g/\sqrt{0.001\,g^2} = 3.16\,\eta per coordinate, and with β2=0.999\beta_2 = 0.999 the second-moment estimate would stay too small for hundreds of steps.

Worked example. A first gradient g1=(100,0.01)g_1 = (100, 0.01). Then m^1=g1\hat m_1 = g_1 and v^1=g12\hat v_1 = g_1^2, so, neglecting the small ε\varepsilon, the first step is approximately η (1,1)\eta\,(1, 1): each coordinate moves by about η\eta against the sign of its gradient, although the two gradients differ by a factor of 10410^4. Plain gradient descent would move the first coordinate 10410^4 times farther than the second.

Figure

Momentum and Adam on a stretched bowl

Paths of gradient descent, momentum and AdamTwo panels of stretched contour ellipses, horizontal on the left and tilted on the right. The blue zigzag of gradient descent and the green arc of momentum are the same in both panels up to the rotation. The red path of Adam heads almost straight for the centre on the left and loops around it; on the right it veers off and then winds slowly.different scales: H diagonalw₀correlated features: the same H rotated by 30°w₀gradient descent, η = 2/(L + μ): 173 | 173 stepsmomentum, β = 0.9, η = 0.05: 48 | 48 stepsAdam, η = 0.2: 13 | 171 stepsPaths of gradient descent, momentum and AdamTwo panels of stretched contour ellipses, horizontal on the left and tilted on the right. The blue zigzag of gradient descent and the green arc of momentum are the same in both panels up to the rotation. The red path of Adam heads almost straight for the centre on the left and loops around it; on the right it veers off and then winds slowly.different scales: H diagonalw₀correlated features:the same H rotated by 30°w₀gradient descent: 173 | 173momentum, β = 0.9: 48 | 48Adam, η = 0.2: 13 | 171
The quadratic Q(w) = ½wᵀHw with eigenvalues 4.5 and 0.045 (κ = 100), exact gradients, the first 40–60 steps of each method; the number of steps until Q falls 1000-fold is given for the left | right panel. Left, the axes are the eigenvectors, as for features on different scales; right, the same bowl rotated by 30°, as for correlated features, with the start rotated too. Gradient descent with the best constant step bounces across the valley (173 steps). Momentum builds up speed along the floor and arrives in 48 steps. Neither method notices the rotation: the right path is a rotated copy of the left one. Adam divides each coordinate's step by that coordinate's typical gradient and heads almost straight for the minimum on the diagonal bowl, overshoots it under its own momentum and loops back (13 steps), but after the rotation the valley no longer runs along an axis, and it is no faster than gradient descent (171 steps).

The figure shows what that buys and what it does not. When the valley runs along the coordinate axes, as it does when features have different scales but are uncorrelated, dividing by v^\sqrt{\hat v} equalizes the curvatures much as standardization did, and Adam needs 13 steps against 173 for gradient descent. When the same valley is rotated, as it is for correlated features, no rescaling of the axes can make it round, and Adam needs 171 steps. Gradient descent and momentum depend only on the geometry of the loss, so they take exactly as many steps in both panels; Adam depends on the coordinate system. Its scaling uses past squared gradients, not an estimate of the full Hessian. The coordinate dependence in this experiment is a limitation of that normalization, not a general guarantee for diagonal curvature.

Three caveats from practice and theory:

  • The step size still matters. On the new fixture, Adam at η=0.003\eta=0.003 ends with excess loss 21.15521.155, while η=0.1\eta=0.1 gives 0.0450.045, under the same 40-epoch budget. The smaller step has not reached the optimum; dividing it tenfold halfway makes the result worse, 28.62028.620. A schedule cannot replace sufficient progress.
  • Adam need not converge. Reddi, Kale and Kumar (2018) construct convex problems on which Adam does not converge to the optimum, for any fixed β1\beta_1, β2\beta_2 in a range that includes the usual 0.90.9 and 0.9990.999 (Theorems 1–3), because the moving average vv forgets a rare large gradient; their AMSGrad uses the running maximum of vv instead.
  • Different solutions. On problems with many minimizers, adaptive methods can converge to different ones than SGD; Wilson et al. (2017) found several tasks where they generalized worse. Weight decay also interacts with the division by v^\sqrt{\hat v}, which is why AdamW applies it separately (weight decay under Adam).

The code checks the analytic gradient against central finite differences and checks the first bias-corrected Adam step explicitly. The optimizer comparison is implemented in NumPy, with shared permutations and no external framework parity claim.

What changed#

Gradient descentSGDSGD with momentumAdam
Gradientexact, O(nd)O(nd)from BB examples, O(Bd)O(Bd)from BB examplesfrom BB examples
Constant stepconverges for a stable step on a smooth convex problempersistent noise generally leaves a nonzero errorstability and noise depend jointly on step, momentum and problemno general convergence guarantee
Dependence on κ\kappa (quadratic, exact gradients)κ\kappaκ\kappaκ\sqrt\kappa with tuned η,β\eta, \betano general rate guaranteed from κ\kappa alone
Memory per weightnonenoneone velocitytwo moments
Typical usesmall smooth problemsconvex models, with a schedulevision networks, with a scheduleTransformers, most deep learning (as AdamW)

Limitations#

  • Noise needs a schedule. When the gradient noise stays nonzero at the minimum, no constant step converges; the schedule adds hyperparameters. The exception is interpolation: if one weight vector fits every example exactly, as in least squares with more features than examples, every per-example gradient vanishes there and constant-step SGD can converge to it. Overparametrized models that fit their training set are close to this regime, the setting of the double-descent caveat.
  • Momentum’s optimal tuning needs μ\mu and LL. The κ\sqrt\kappa rate holds for the best parameters; with β=0.9\beta = 0.9 and a guessed η\eta the gain is smaller, and too much momentum oscillates.
  • Adaptive methods see only the diagonal. Correlated features leave a rotated valley that per-coordinate steps cannot straighten.
  • No method removes the need to tune η\eta. Defaults work for some model families and fail by orders of magnitude for others.
  • Theory and practice diverge for networks. The guarantees are for convex losses; for neural networks the choices rest on experiments.

What you should remember#

  • A minibatch gradient is an unbiased estimate of the full gradient with covariance Σ/B\Sigma/B: error ∝1/B\propto 1/\sqrt B, cost ∝B\propto B.
  • With a constant step, SGD settles in a noise ball: excess loss about ηs2/4\eta s^2/4 in one dimension, ησ2tr⁡(H)/4\eta\sigma^2\operatorname{tr}(H)/4 for least squares. Decreasing steps with ∑ηk=∞\sum\eta_k = \infty, ∑ηk2<∞\sum\eta_k^2 < \infty converge; in practice, schedules.
  • Momentum, v←βv+gv \leftarrow \beta v + g, w←w−ηvw \leftarrow w - \eta v, accumulates consistent directions and cancels oscillating ones; on quadratics it needs κ\sqrt\kappa instead of κ\kappa steps. Nesterov’s look-ahead keeps that rate on all smooth strongly convex functions.
  • AdaGrad divides by the root of the accumulated squared gradients (good for sparse features, steps shrink forever); RMSProp by a moving average of them.
  • Adam = momentum + RMSProp + bias correction 1/(1−βk)1/(1 - \beta^k); its first step is approximately η sign(g)\eta\,\mathrm{sign}(g) when ε\varepsilon is negligible. Coordinate normalization can help with scale differences but does not whiten correlated directions; the step size still needs tuning.

Code#

The noise recurrence, minibatch sampling, the deterministic quadratic, the analytic gradient check and the new NumPy optimizer experiment. The synthetic generator is self-contained and downloads no data:

import numpy as np

rng = np.random.default_rng(0)

# the noise ball in one dimension: Q(w) = w^2 / 2, stochastic gradient w + noise with variance 1
for eta in (0.1, 0.01):
    w = np.zeros(20_000)                                 # 20,000 independent runs from w = 0
    for k in range(int(20 / eta)):
        w = w - eta * (w + rng.normal(size=w.size))
    print(eta, round(w.var(), 4), round(eta / (2 - eta), 4))   # simulated and stationary variance of w
# 0.1 0.053 0.0526 | 0.01 0.005 0.005

# Original synthetic inputs; sample gradients independently with replacement.
def make_data():
    # Independent dimensionless simulated inputs, with one deliberately redundant pair.
    rng = np.random.default_rng(20261113)
    base = rng.normal(size=(240, 8))
    X = base.copy()
    X[:, 1] = base[:, 0] + 0.08 * base[:, 1]
    y = 20 + X @ np.array([4., 4., -3., 2., 0., 0., 0., 0.])
    y += 4 * rng.normal(size=len(X))
    return X, y

X, y = make_data()
X = (X - X.mean(0)) / X.std(0); y = y - y.mean(); n = len(y)
G = X * (-y)[:, None]; full_gradient = G.mean(0)
noise_rng = np.random.default_rng(20261114)
for B in (1, 8, 64):
    idx = noise_rng.integers(0, n, size=(6000, B))
    errors = G[idx].mean(1) - full_gradient
    print(B, round(float(np.sqrt(np.mean(np.sum(errors ** 2, axis=1)))), 2),
          round(float(np.sqrt(np.sum(np.var(G, axis=0)) / B)), 2))
# 1 28.99 28.47 | 8 10.05 10.07 | 64 3.54 3.56

# a quadratic with eigenvalues 0.045 and 4.5 (kappa = 100): steps to shrink the excess loss 1000-fold
mu, L = 0.045, 4.5
c, s = np.cos(np.pi / 6), np.sin(np.pi / 6); R = np.array([[c, -s], [s, c]])
H1 = np.diag([L, mu]); H2 = R @ H1 @ R.T                 # the same bowl, axis-aligned and rotated by 30 degrees
def steps(H, w0, method, eta, beta=0.0, K=2000):
    w, v, m, s2 = w0.copy(), np.zeros(2), np.zeros(2), np.zeros(2)
    q0 = w0 @ H @ w0
    for k in range(1, K + 1):
        g = H @ w
        if method == 'gd': w = w - eta * g
        if method == 'momentum': v = beta * v + g; w = w - eta * v
        if method == 'nesterov':
            g = H @ (w - eta * beta * v); v = beta * v + g; w = w - eta * v
        if method == 'adam':
            m = 0.9 * m + 0.1 * g; s2 = 0.999 * s2 + 0.001 * g * g
            w = w - eta * (m / (1 - 0.9 ** k)) / (np.sqrt(s2 / (1 - 0.999 ** k)) + 1e-8)
        if w @ H @ w < 1e-3 * q0: return k
w0 = np.array([-2.4, 1.6])
rk = np.sqrt(L / mu)
print(round((L - mu) / (L + mu), 3), round((rk - 1) / (rk + 1), 3),
      steps(H1, w0, 'gd', 2 / (L + mu)), steps(H1, w0, 'momentum', 4 / (np.sqrt(L) + np.sqrt(mu)) ** 2, ((rk - 1) / (rk + 1)) ** 2),
      steps(H1, w0, 'nesterov', 1 / L, (rk - 1) / (rk + 1)))
# 0.98 0.818 173 39 17: asymptotic per-step factors of GD and momentum; steps of GD, optimal heavy ball, Nesterov
w, v, norms = w0.copy(), np.zeros(2), []
for _ in range(10):
    v = ((rk - 1) / (rk + 1)) ** 2 * v + H1 @ w; w = w - 4 / (np.sqrt(L) + np.sqrt(mu)) ** 2 * v; norms.append(np.linalg.norm(w))
print(round(float(np.linalg.norm(w0)), 2), round(float(max(norms)), 2), int(np.argmax(norms)) + 1)
# 2.88 8.98 4: the optimal heavy ball first moves away, error norm 2.88 -> 8.98 after 4 steps
for name, H, start in (('aligned', H1, w0), ('rotated', H2, R @ w0)):
    print(name, steps(H, start, 'gd', 2 / (L + mu)), steps(H, start, 'momentum', 0.05, 0.9), steps(H, start, 'adam', 0.2))
# aligned 173 48 13 | rotated 173 48 171

# Neglect epsilon for this demonstration: the first corrected step is eta * sign(g).
g1 = np.array([100.0, 0.01])
m1, v1 = 0.1 * g1, 0.001 * g1 ** 2
print((m1 / 0.1) / np.sqrt(v1 / 0.001), (m1 / np.sqrt(v1)).round(2))   # [1. 1.] [3.16 3.16]

# Independent numerical gradient and first-step checks.
loss = lambda w: np.mean((X @ w - y) ** 2) / 2
probe = np.linspace(-0.4, 0.7, X.shape[1]); h = 1e-5
finite = np.array([(loss(probe + h * e) - loss(probe - h * e)) / (2*h) for e in np.eye(len(probe))])
analytic = X.T @ (X @ probe - y) / n
assert np.max(abs(finite - analytic)) < 1e-7
first_gradient = np.array([100., 0.01])
first_m = 0.1 * first_gradient; first_v = 0.001 * first_gradient ** 2
assert np.allclose((first_m / 0.1) / (np.sqrt(first_v / 0.001) + 1e-8), first_gradient / (abs(first_gradient) + 1e-8))

def train(X, y, method, eta, cut=False):
    # A shared NumPy permutation for every optimizer makes the finite comparison explicit.
    out = []
    optimum = np.linalg.lstsq(X, y, rcond=None)[0]
    minimum = np.mean((X @ optimum - y) ** 2) / 2
    for seed in range(5):
        rng = np.random.default_rng(400 + seed)
        w = np.zeros(X.shape[1]); velocity = w.copy(); m = w.copy(); v = w.copy()
        step = 0
        for epoch in range(40):
            rate = eta / 10 if cut and epoch >= 20 else eta
            indices = rng.permutation(len(y))
            for start in range(0, len(y), 24):
                idx = indices[start:start + 24]
                g = X[idx].T @ (X[idx] @ w - y[idx]) / len(idx)
                step += 1
                if method == "sgd":
                    w -= rate * g
                elif method == "momentum":
                    velocity = 0.9 * velocity + g
                    w -= rate * velocity
                elif method == "adam":
                    m = 0.9 * m + 0.1 * g
                    v = 0.999 * v + 0.001 * g * g
                    w -= rate * (m / (1 - 0.9 ** step)) / (np.sqrt(v / (1 - 0.999 ** step)) + 1e-8)
                else:
                    raise ValueError(method)
        out.append(float(np.mean((X @ w - y) ** 2) / 2 - minimum))
    return {"mean": float(np.mean(out)), "seed_results": out}

w_hat = np.linalg.lstsq(X, y, rcond=None)[0]
print(round(loss(w_hat), 3), round(float(np.linalg.cond(X.T @ X)), 1))  # 8.456 568.9
for method, rate in [('sgd', 0.03), ('sgd', 0.15), ('momentum', 0.015), ('adam', 0.003), ('adam', 0.1)]:
    print(method, rate, round(train(X, y, method, rate)['mean'], 3), round(train(X, y, method, rate, True)['mean'], 3))
# sgd 0.03 0.035 0.035 | sgd 0.15 0.116 0.029 | momentum 0.015 0.054 0.030
# adam 0.003 21.155 28.620 | adam 0.1 0.045 0.036

Next#

Least squares can now be fitted for any nn and dd, by formula or by descent. Being able to fit it does not make the fit good. With many features, or features that nearly repeat each other, the least-squares note showed coefficients that swing with every draw of the noise and a training R2R^2 that rises while the validation R2R^2 collapses. The next note adds a penalty on the size of the weights: ridge and the lasso, the priors behind them, and how to choose the penalty’s strength by validation.

The optimizers of this note train the networks of the other courses: the Deep Learning course adds warm-up, decoupled weight decay and gradient clipping to them, Adam and AdamW are the defaults of the Generative Models training runs, and the next section of this course uses them for neural networks.

References#