Skip to content

Module 08

Anurag Prasad edited this page Nov 8, 2026 · 10 revisions

Module 08 — Deep Network Optimization and Loss Landscapes

⬅️ Module 07 · 🗺️ Curriculum · 🏠 Home · Module 09 ➡️

Level: Intermediate–Advanced · Prerequisites: Modules 01, 02, 06, 07 · Time: about 8–10 hours

On this page: Overview and learning goals · Beginner: the big picture · Core concepts and derivations · Worked example · Implementation · Advanced topics · Pitfalls and best practices · Conceptual questions and answers · Sources and further reading


Overview and learning goals

Deep-network losses are non-convex, ill-conditioned and noisy. Plain SGD works but slowly and fragilely; modern training relies on momentum, adaptive per-parameter step sizes, learning-rate schedules, clipping and diagnostics. This module develops these methods from the quadratic model so you can understand why each helps.

After this module you should be able to:

  • classify critical points and explain convexity, saddles, plateaus and cliffs;
  • derive the update rules of momentum, Nesterov, AdaGrad, RMSProp, Adam and AdamW and explain Adam's bias correction;
  • describe newer optimisers (Lion, Sophia, Muon) at a conceptual level;
  • design a learning-rate schedule with warm-up and decay, and apply gradient clipping.

Beginner: the big picture

Picture the loss as a landscape and the parameters as a ball rolling downhill. Narrow valleys make plain gradient descent zigzag; momentum lets the ball build up speed along the valley floor; adaptive methods give each parameter its own step size; schedules start gently and shrink steps near the end.

flowchart TD
    G["Gradient g_t"] --> M["Momentum: smooth direction over time"]
    G --> A["Adaptive scaling: divide by sqrt of running g^2"]
    M --> AD["Adam = momentum + adaptive scaling"]
    A --> AD
    AD --> W["AdamW: add decoupled weight decay"]
    S["Schedule: warm-up then decay eta_t"] --> U
    W --> U["Parameter update"]
    C["Gradient clipping"] --> G
Loading

Core concepts and derivations

Local/global minima, saddle points, plateaus and cliffs

At a critical point $\nabla L=0$ the Hessian eigenvalues classify it: all $>0$ minimum, all $<0$ maximum, mixed signs saddle (like $x^2-y^2$, Figure 8.2). In high dimension, a random critical point is a saddle far more often than a minimum; Dauphin et al. (2014) argue saddles and plateaus, not poor local minima, are the main obstacle. Plateaus have tiny gradients; cliffs have huge ones (common in RNNs, Module 12).

Convexity and non-convex objectives

$L$ is convex if $L(\lambda\theta+(1-\lambda)\theta')\le\lambda L(\theta)+(1-\lambda)L(\theta')$ — equivalently $H\succeq0$. Convex problems have no spurious local minima. Linear/logistic regression are convex; neural-network losses are not, yet SGD reliably finds good solutions, partly because many minima generalise similarly and overparameterised networks have connected low-loss regions.

Loss contours, curvature and ill-conditioning

For $L=\tfrac12\theta^\top H\theta$ with eigenvalues $\lambda_i\in[\mu,L_{\max}]$, GD is stable iff $\eta<2/L_{\max}$ and converges at rate $1-\eta\mu$ in the flattest direction, so with $\eta\approx1/L_{\max}$ it needs $\sim\kappa=L_{\max}/\mu$ iterations. The best constant step $\eta=2/(L_{\max}+\mu)$ gives contraction $\frac{\kappa-1}{\kappa+1}$.

Gradient descent vs heavy-ball momentum on an ill-conditioned quadratic

Figure 8.1 — Quadratic with curvatures 1 and 25 ($\kappa=25$). Optimal GD contracts by $0.923$ per step and zigzags; optimal heavy-ball ($\eta=1/9,\beta=4/9$) contracts by $0.667$, needing roughly five times fewer steps for the same accuracy ($\ln0.923/\ln0.667\approx0.2$). Original figure (figures/make_figs_1.py).

Batch GD, SGD and mini-batch SGD

See Module 06. The gradient noise acts like a temperature: it lets SGD leave sharp minima but sets a noise floor $\propto\eta/B$ at a constant step size.

Momentum and Nesterov

Heavy-ball momentum (Polyak 1964): $\mathbf{v}_{t+1}=\beta\mathbf{v}t-\eta\mathbf{g}t$, $\ \theta{t+1}=\theta_t+\mathbf{v}{t+1}$. Unrolled, $\mathbf{v}$ is an exponentially weighted sum of past gradients: oscillating components cancel, consistent ones accumulate (effective step $\eta/(1-\beta)$). With optimal tuning on a quadratic the rate improves from $\frac{\kappa-1}{\kappa+1}$ to $\frac{\sqrt\kappa-1}{\sqrt\kappa+1}$ — iterations scale with $\sqrt\kappa$ instead of $\kappa$. Nesterov evaluates the gradient at the look-ahead point: $\mathbf{g}_t=\nabla L(\theta_t+\beta\mathbf{v}_t)$, and achieves the optimal $O(1/t^2)$ rate for convex smooth problems.

AdaGrad, RMSProp, Adam and AdamW

Per-parameter scaling by gradient history:

  • AdaGrad: $G_t=G_{t-1}+\mathbf{g}_t^2$, $\ \theta\leftarrow\theta-\eta,\mathbf{g}_t/(\sqrt{G_t}+\epsilon)$. Good for sparse features; the effective rate only decays.
  • RMSProp: $s_t=\rho s_{t-1}+(1-\rho)\mathbf{g}_t^2$ replaces the sum by an exponential average.
  • Adam (Kingma & Ba 2015):

$$ \mathbf{m}_t=\beta_1\mathbf{m}_{t-1}+(1-\beta_1)\mathbf{g}_t,\quad \mathbf{v}_t=\beta_2\mathbf{v}_{t-1}+(1-\beta_2)\mathbf{g}_t^2,\quad \hat{\mathbf{m}}_t=\frac{\mathbf{m}_t}{1-\beta_1^t},\ \ \hat{\mathbf{v}}_t=\frac{\mathbf{v}_t}{1-\beta_2^t},\quad \theta_t=\theta_{t-1}-\eta\frac{\hat{\mathbf{m}}_t}{\sqrt{\hat{\mathbf{v}}_t}+\epsilon}. $$

Bias correction: with $\mathbf{m}_0=0$ and stationary $\mathbb{E}[\mathbf{g}]$, $\mathbb{E}[\mathbf{m}_t]=(1-\beta_1^t)\mathbb{E}[\mathbf{g}]$, so dividing by $1-\beta_1^t$ removes the initial bias toward 0. Defaults $\beta_1=0.9$, $\beta_2=0.999$, $\epsilon=10^{-8}$.

  • AdamW (Loshchilov & Hutter 2019) decouples weight decay: $\theta\leftarrow\theta-\eta\bigl(\hat{\mathbf{m}}/(\sqrt{\hat{\mathbf{v}}}+\epsilon)+\lambda\theta\bigr)$. Adding $\lambda\theta$ to the gradient (L2) instead gets rescaled by the adaptive denominator, so regularisation strength would vary per parameter; decoupling fixes this.

Newer optimiser families

  • Lion (Chen et al. 2023) uses only the sign of an interpolation of momentum and gradient, $\theta\leftarrow\theta-\eta(\operatorname{sign}(\beta_1\mathbf{m}+(1-\beta_1)\mathbf{g})+\lambda\theta)$, storing a single momentum buffer.
  • Sophia (Liu et al. 2023) preconditions with a cheap running diagonal Hessian estimate and clips the update to control worst-case step size.
  • Muon (K. Jordan et al., 2024) treats matrix parameters as matrices: it orthogonalises the momentum update (via a few Newton–Schulz iterations) so all singular directions move at comparable rates.

These are active research; benchmark them against tuned AdamW for your setting rather than assuming superiority.

Learning-rate schedules, warm-up and cosine decay

Common schedules: step decay; cosine $\eta_t=\eta_{\min}+\tfrac12(\eta_{\max}-\eta_{\min})\bigl(1+\cos\tfrac{\pi t}{T}\bigr)$ (Loshchilov & Hutter 2017); linear decay. Warm-up ramps $\eta$ from ~0 over the first steps: early on Adam's second-moment estimate is unreliable and large-batch/Transformer training is unstable at full rate.

Saddle surface and learning-rate schedules

Figure 8.2 — Left: saddle $f=x^2-y^2$ (minimum along $x$, maximum along $y$). Right: constant, step, cosine and warm-up+cosine schedules. Original figure (figures/make_figs_1.py).

Gradient clipping and optimiser diagnostics

Clip by global norm: $\mathbf{g}\leftarrow\mathbf{g}\cdot\min\bigl(1,c/\lVert\mathbf{g}\rVert_2\bigr)$ — it preserves direction and tames cliffs (Pascanu et al. 2013). Monitor: loss and gradient-norm curves, update-to-weight ratio $\lVert\Delta\theta\rVert/\lVert\theta\rVert$ (often $\sim10^{-3}$), fraction of dead activations, and per-layer gradient norms.

Worked example

First Adam step. Let $g_1=0.5$, $\beta_1=0.9$, $\beta_2=0.999$. $m_1=0.1\cdot0.5=0.05$, $v_1=0.001\cdot0.25=2.5\times10^{-4}$; $\hat m_1=0.05/0.1=0.5$, $\hat v_1=2.5\times10^{-4}/0.001=0.25$, so the step is $\eta\cdot0.5/(0.5+\epsilon)\approx\eta$. The first update has magnitude $\approx\eta$ regardless of the gradient's scale — a hallmark of Adam (and the reason warm-up helps).

Momentum accumulation. Constant gradient $g$: $v_t\to-\eta g/(1-\beta)$; for $\beta=0.9$ the effective step is $10\eta g$.

Implementation

import numpy as np

def adam(grad_fn, theta, steps=200, lr=0.1, b1=0.9, b2=0.999, eps=1e-8, wd=0.0):
    m = v = np.zeros_like(theta)
    for t in range(1, steps + 1):
        g = grad_fn(theta)
        m = b1 * m + (1 - b1) * g; v = b2 * v + (1 - b2) * g * g
        mh, vh = m / (1 - b1 ** t), v / (1 - b2 ** t)
        theta = theta - lr * (mh / (np.sqrt(vh) + eps) + wd * theta)     # AdamW when wd>0
    return theta

H = np.diag([1., 25.]); print(adam(lambda th: H @ th, np.array([-4., 1.2])))   # near [0, 0]
import math, torch
opt = torch.optim.AdamW(model.parameters(), lr=3e-4, betas=(0.9, 0.95), weight_decay=0.1)
warmup, total = 1_000, 100_000
lr_lambda = lambda s: min(1.0, s / warmup) * 0.5 * (1 + math.cos(math.pi * min(s, total) / total))  # warm-up x cosine
sched = torch.optim.lr_scheduler.LambdaLR(opt, lr_lambda)
# each step:  loss.backward(); torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0); opt.step(); sched.step(); opt.zero_grad()

Advanced topics

  • Convergence theory: SGD $O(1/\sqrt t)$ (convex); Adam can fail to converge in constructed convex cases (Reddi et al. 2018, AMSGrad fix), yet works in practice.
  • Second-order and preconditioned methods: Newton, L-BFGS, K-FAC/Shampoo approximate $H^{-1}$ or the Fisher.
  • Sharpness and generalisation: flat minima, SAM (sharpness-aware minimisation), large-batch generalisation gap.
  • Edge of stability: full-batch GD self-stabilises with $\lambda_{\max}(H)\approx2/\eta$ (Cohen et al. 2021).
  • Large-batch scaling: linear LR scaling with warm-up; LARS/LAMB layer-wise scaling.
  • Loss-landscape visualisation via filter-normalised random slices (Li et al. 2018).

Pitfalls and best practices

  • Applying L2 inside Adam when you meant weight decay (use AdamW; do not decay biases/norm parameters).
  • Skipping warm-up for Transformers or large batches.
  • Clipping after the optimiser step, or per-parameter instead of global norm.
  • Comparing optimisers without tuning $\eta$ for each.
  • Forgetting optimizer.zero_grad().

Conceptual questions and answers

Q1. Why does momentum help in narrow valleys?

Gradient components across the valley alternate in sign and cancel in the exponential average, while components along the valley floor add up, accelerating progress.

Q2. Derive the effective step size of momentum under a constant gradient.

$v=\beta v-\eta g$ has fixed point $v=-\eta g/(1-\beta)$, so the effective step is $\eta/(1-\beta)$ times $g$ — 10× for $\beta=0.9$.

Q3. Why does Adam need bias correction?

$\mathbf{m}_0=\mathbf{v}_0=0$ biases early estimates toward zero by factors $(1-\beta^t)$; dividing by them yields unbiased estimates (for stationary gradients).

Q4. What is the difference between L2 regularisation and weight decay in Adam?

With L2 the penalty gradient $\lambda\theta$ passes through the adaptive denominator, so weights with large gradient history are decayed less. AdamW applies decay directly to $\theta$, giving uniform, learning-rate-scaled shrinkage.

Q5. Why are saddle points more of a concern than local minima in high dimensions?

A critical point needs all $d$ Hessian eigenvalues positive to be a minimum; with many dimensions, mixed signs (saddles) are overwhelmingly more common, and gradients become tiny around them.

Q6. Why use warm-up?

Early in training second-moment estimates are noisy and weights are random; a large step can destabilise training. Warm-up lets statistics settle before the full learning rate.

Q7. How does gradient clipping by norm work and when is it needed?

It rescales $\mathbf{g}$ to norm $c$ when $\lVert\mathbf{g}\rVert>c$, keeping direction. It prevents rare huge gradients (cliffs, exploding RNN gradients, loss spikes) from derailing training.

Q8. Which iteration count scaling do plain GD and momentum have on quadratics?

GD needs $O(\kappa)$ iterations; optimally tuned momentum $O(\sqrt\kappa)$.

Q9. When might SGD+momentum outperform Adam?

Often in vision tasks with well-tuned schedules, where it can generalise better; Adam(W) dominates in Transformers and sparse-gradient settings. The best choice is empirical.

Sources and further reading

  • Polyak, B. T. (1964). Some methods of speeding up the convergence of iteration methods. USSR Comput. Math. Math. Phys., 4(5).
  • Nesterov, Y. (1983). A method for solving the convex programming problem with convergence rate $O(1/k^2)$. Dokl. Akad. Nauk SSSR, 269.
  • Duchi, J., Hazan, E., & Singer, Y. (2011). Adaptive subgradient methods. JMLR, 12.
  • Tieleman, T., & Hinton, G. (2012). Lecture 6.5 — RMSProp. COURSERA: Neural Networks for Machine Learning.
  • Kingma, D. P., & Ba, J. (2015). Adam: a method for stochastic optimization. ICLR. arXiv:1412.6980.
  • Reddi, S. J., Kale, S., & Kumar, S. (2018). On the convergence of Adam and beyond. ICLR.
  • Loshchilov, I., & Hutter, F. (2017). SGDR: stochastic gradient descent with warm restarts. ICLR.
  • Loshchilov, I., & Hutter, F. (2019). Decoupled weight decay regularization. ICLR. arXiv:1711.05101.
  • Pascanu, R., Mikolov, T., & Bengio, Y. (2013). On the difficulty of training recurrent neural networks. ICML.
  • Dauphin, Y., et al. (2014). Identifying and attacking the saddle point problem in high-dimensional non-convex optimization. NeurIPS.
  • Chen, X., et al. (2023). Symbolic discovery of optimization algorithms (Lion). arXiv:2302.06675.
  • Liu, H., et al. (2023). Sophia: a scalable stochastic second-order optimizer for language model pre-training. arXiv:2305.14342.
  • Jordan, K., et al. (2024). Muon: an optimizer for hidden layers in neural networks (technical write-up).
  • Cohen, J., et al. (2021). Gradient descent on neural networks typically occurs at the edge of stability. ICLR.
  • Li, H., et al. (2018). Visualizing the loss landscape of neural nets. NeurIPS.

⬅️ Module 07 · 🗺️ Curriculum · 🏠 Home · Module 09 ➡️

🎓 Deep Learning Hub

🏠 Home · 🗺️ Curriculum · 🧭 Learning paths

❓ Question bank · 📖 Glossary · 📚 References

Jump to module:

01 02 03 04 05 06 07 08 09 10 11 12

13 14 15 16 17 18 19 20 21 22 23 24

Part 1 · Mathematical foundations
Part 2 · Neural network fundamentals
Part 3 · Training deep networks
Part 4 · Core architectures
Part 5 · Representation and generative learning
Part 6 · Specialised, modern and responsible deep learning
Reference and meta

Clone this wiki locally