Skip to content
ml-recall

Topic notes

Optimization & Calculus

Calculus for training — critical points, convexity, gradient descent and step sizes, SGD, momentum, Adagrad/RMSProp/Adam and automatic differentiation.

4-min read AI-checked

Practise 143 questions Take a test

Key ideas

Training = minimising a loss L(θ)L(\theta). The gradient ∇L\nabla L is the vector of partial derivatives; it points uphill, so we step against it1.

Critical points (∇f=0\nabla f=0) are minima, maxima or saddle points. In 1-D, f′′>0f''>0 ⇒ local min, f′′<0f''<0 ⇒ local max, f′′=0f''=0 ⇒ no conclusion (x3x^3, x4x^4, −x4-x^4). In nn-D, look at the Hessian HH: positive definite ⇒ min, negative definite ⇒ max, mixed signs ⇒ saddle. A maximum at an endpoint of an interval, or at a kink, need not have f′=0f'=0. Gradient descent rarely stays at a saddle: a tiny offset along a direction of negative curvature grows geometrically.

Convexity. A set is convex if it contains every segment between its points (balls of any norm, half-spaces, lines). ff is convex if f(λx+(1−λ)y)≤λf(x)+(1−λ)f(y)f(\lambda x+(1-\lambda)y)\le\lambda f(x)+(1-\lambda)f(y), equivalently H⪰0H\succeq0; then every local minimum is global. Sums and maxima of convex functions are convex; minima are not, and neither is ReLU(x)−ReLU(x−1)\mathrm{ReLU}(x)-\mathrm{ReLU}(x-1). Neural network losses are non-convex — e.g. permuting the kk hidden units gives k!k! equivalent weight settings.

Gradient descent (GD): x←x−η∇f(x)x\leftarrow x-\eta\nabla f(x). Too small η\eta crawls, too large overshoots and diverges1. On f=λ2x2f=\frac{\lambda}{2}x^2 the update is x←(1−ηλ)xx\leftarrow(1-\eta\lambda)x, which converges iff 0<η<2/λ0<\eta<2/\lambda3. With several curvatures the steepest one caps η\eta (η<2/λmax⁡\eta<2/\lambda_{\max}) while the flattest one sets the speed, so a large condition number κ=λmax⁡/λmin⁡\kappa=\lambda_{\max}/\lambda_{\min} means slow progress3. Given the gradient, one update costs O(D)O(D) for DD parameters. Stop when the gradient or the updates become tiny, or after an iteration budget.

Second-order ideas1. Newton: x←x−H−1∇fx\leftarrow x-H^{-1}\nabla f — the minimiser of the local quadratic Taylor model, exact in one step on a quadratic; on non-convex ff use ∣H∣|H| so the step still goes downhill. A full Hessian has P2P^2 entries (1 million parameters → 101210^{12} numbers), so practice uses diagonal preconditioning, a per-coordinate learning rate — it only helps when the steep and flat directions are aligned with the axes; rotate the problem and the benefit is gone7.

SGD2. One example (or a minibatch) per step: cost O(1)O(1) instead of O(n)O(n). The stochastic gradient is an unbiased estimate of the full gradient; averaging over a minibatch of bb i.i.d. examples divides its variance by bb (SD by b\sqrt b). Because the noise does not vanish at the optimum, η\eta must decay; for convex problems ηt∝1/t\eta_t\propto1/\sqrt t gives an O(1/T)O(1/\sqrt T) rate2. Sampling nn examples with replacement touches only about 1−e−1≈63%1-e^{-1}\approx63\% of them 2. Full-batch GD is the only one of GD/SGD/minibatch whose updates do not depend on the order of the data.

Momentum keeps a leaky average vt=βvt−1+gtv_t=\beta v_{t-1}+g_t, x←x−ηvtx\leftarrow x-\eta v_t. It averages about 1/(1−β)1/(1-\beta) recent gradients, so noise cancels and the effective step is η/(1−β)\eta/(1-\beta) (10× for β=0.9\beta=0.9)3; it damps oscillation across a narrow valley and accepts larger η\eta.

Adaptive methods (per-coordinate scaling):

Method State Step
Adagrad st=st−1+gt2s_t=s_{t-1}+g_t^2 η gt/st+ϵ\eta\,g_t/\sqrt{s_t+\epsilon} — rate decays like t−1/2t^{-1/2}4,7
RMSProp st=γst−1+(1−γ)gt2s_t=\gamma s_{t-1}+(1-\gamma)g_t^2 same; leaky average fixes the decay4
Adam vt=β1vt−1+(1−β1)gtv_t=\beta_1v_{t-1}+(1-\beta_1)g_t, st=β2st−1+(1−β2)gt2s_t=\beta_2s_{t-1}+(1-\beta_2)g_t^2 η v^t/(s^t+ϵ)\eta\,\hat v_t/(\sqrt{\hat s_t}+\epsilon), v^t=vt1−β1t\hat v_t=\frac{v_t}{1-\beta_1^t}, s^t=st1−β2t\hat s_t=\frac{s_t}{1-\beta_2^t}5

Adam (defaults β1=0.9\beta_1=0.9, β2=0.999\beta_2=0.999) keeps two extra numbers per parameter; bias correction undoes the zero initialisation5. On step 1, v^1/s^1=sign(g1)\hat v_1/\sqrt{\hat s_1}=\mathrm{sign}(g_1), so the first move has size η\eta whatever the gradient's scale. Its learning rate should still decay: near a minimum, noisy gradients keep v^/s^\hat v/\sqrt{\hat s} from vanishing, so the iterates jitter at a scale set by η\eta. Schedules: step or polynomial decay, cosine ηt=ηT+η0−ηT2(1+cos⁡πtT)\eta_t=\eta_T+\frac{\eta_0-\eta_T}{2}(1+\cos\frac{\pi t}{T}) (slow decay at first, a small rate to refine at the end), and warm-up — raise η\eta from a small value, because a large rate at the start, when updates from random weights are large and poorly aimed, can diverge8.

Computing derivatives. Symbolic, numerical (finite differences — truncation error for large hh, round-off for tiny hh) and automatic differentiation, exact to working precision6. Forward mode carries a tangent with each value (dual numbers a+bεa+b\varepsilon, ε2=0\varepsilon^2=0) and needs one pass per input; reverse mode (backpropagation) needs one pass per output, ideal for a scalar loss with millions of parameters6.

Formulas

∇w (w⊤Aw)=(A+A⊤)w,∇v∥v∥2=v∥v∥2,∇Wlog⁡∣det⁡W∣=(W−1)⊤\nabla_{w}\,(w^\top Aw)=(A+A^\top)w,\qquad \nabla_v\lVert v\rVert_2=\frac{v}{\lVert v\rVert_2},\qquad \nabla_W\log|\det W|=(W^{-1})^\top ∂∂xlog⁡(ex+ey)=exex+ey,min⁡x 12x⊤Qx+c⊤x: x∗=−Q−1c  (Q≻0)\frac{\partial}{\partial x}\log(e^x+e^y)=\frac{e^x}{e^x+e^y},\qquad \min_x\ \tfrac12x^\top Qx+c^\top x:\ x^*=-Q^{-1}c\ \ (Q\succ0)

Chain rule for u=f(x(a),y(a))u=f(x(a),y(a)): ∂u∂a=∂f∂x∂x∂a+∂f∂y∂y∂a\frac{\partial u}{\partial a}=\frac{\partial f}{\partial x}\frac{\partial x}{\partial a}+\frac{\partial f}{\partial y}\frac{\partial y}{\partial a}.

Worked example

f(x)=12(x12+10x22)f(x)=\frac12(x_1^2+10x_2^2), so ∇f=(x1, 10x2)\nabla f=(x_1,\,10x_2) and each GD step multiplies the coordinates by 1−η1-\eta and 1−10η1-10\eta. Stability needs ∣1−10η∣<1|1-10\eta|<1, i.e. η<0.2\eta<0.2. From (1,1)(1,1) with η=0.15\eta=0.15: one step gives (0.85, −0.5)(0.85,\,-0.5) — x2x_2 flips sign but shrinks. With η=0.25\eta=0.25 the factor is −1.5-1.5 and x2x_2 explodes, although x1x_1 would still converge. κ=10\kappa=10: x1x_1 loses at most 20% per step at the largest stable η\eta.

In code

import torch

for g in [1000.0, -0.002]:                    # very different gradient sizes
    w = torch.tensor([0.0], requires_grad=True)
    opt = torch.optim.Adam([w], lr=0.01)
    (g * w).sum().backward()                  # dL/dw = g
    opt.step()
    print(round(w.item(), 6))                 # -0.01, then 0.01

x = torch.tensor([1.0, 1.0], requires_grad=True)
f = 0.5 * (x[0] ** 2 + 10 * x[1] ** 2)
f.backward()
print(x.grad)                                 # tensor([ 1., 10.])

Common pitfalls

References

  1. Dive into Deep Learning — Sec. 12.3.1 One-Dimensional Gradient Descent; 12.3.2 Multivariate Gradient Descent; 12.3.3 Adaptive Methods (Newton's Method, Preconditioning, Line Search)
  2. Dive into Deep Learning — Sec. 12.4.1 Stochastic Gradient Updates; 12.4.2 Dynamic Learning Rate; 12.4.3 Convergence Analysis for Convex Objectives; 12.4.4 Stochastic Gradients and Finite Samples
  3. Dive into Deep Learning — Sec. 12.6.1 Basics (Leaky Averages; An Ill-conditioned Problem; Effective Sample Weight); 12.6.3 Theoretical Analysis
  4. Dive into Deep Learning — Sec. 12.8.1 The Algorithm (recap of Adagrad and the leaky-average fix)
  5. Dive into Deep Learning — Sec. 12.10.1 The Algorithm; 12.10.3 Yogi; 12.10.4 Summary
  6. Wikipedia: Automatic differentiation — Difference from other differentiation methods; Forward and reverse accumulation (Two types of automatic differentiation; Forward accumulation; Reverse accumulation); Automatic differentiation using dual numbers
  7. Dive into Deep Learning — Sec. 12.7.2 Preconditioning; 12.7.3 The Algorithm
  8. Dive into Deep Learning — Sec. 12.11.3.3 Cosine Scheduler; 12.11.3.4 Warmup