Simple Algorithm
Deep Learning · Activation · 17 min

Optimizing Deep Networks

Noisy gradients, adaptive steps and the strange landscapes of deep networks.

A deep network is a function with millions or billions of adjustable numbers, and training means finding values for all of them that make a loss small. No formula gives those values. An optimizer starts from random ones and takes many thousands of small steps downhill, each guided by a gradient estimated from a handful of examples. How big the steps are, what to do with the noise and how each parameter's step adapts decide whether a network trains at all.

What you’ll learn

  • Explain gradient descent as repeated steps against the gradient, and predict from the curvature when a learning rate is too small, about right or too large (η<2/h\eta<2/h for a valley of curvature hh).
  • Describe mini-batch SGD: why cheap, noisy gradients win, how the batch size sets the noise, and why a constant learning rate leaves the loss jittering above its minimum.
  • Compare gradient descent, momentum and Adam on a narrow valley, and name the standard optimizers for transformers and for convolutional networks.
  • Explain why learning rates are warmed up and decayed, and describe what deep-network loss landscapes look like: saddles, flat and sharp regions, and the effect of overparameterization.

Downhill in a million dimensions

A network fθf_{\boldsymbol\theta} is controlled by its parameters θ\boldsymbol\theta, all of its weights and biases: a few thousand in a toy model, billions in a large language model. How badly it does on the nn training examples is summed up in one number, the training loss

L(θ)=1n∑i=1nℓ(fθ(xi),yi).\loss(\boldsymbol\theta)=\frac1n\sum_{i=1}^n\ell\big(f_{\boldsymbol\theta}(\mathbf x_i),y_i\big).

Training is optimization: find a θ\boldsymbol\theta that makes L\loss small. Backpropagation supplies the gradient ∇L(θ)\nabla\loss(\boldsymbol\theta), one partial derivative per parameter, which points in the direction in which the loss rises fastest. Gradient descent steps the other way, over and over:

θt+1=θt−η ∇L(θt)\boldsymbol\theta_{t+1}=\boldsymbol\theta_t-\eta\,\nabla\loss(\boldsymbol\theta_t)
The learning rate η\eta sets the step size. It is the most important setting in deep learning: too small and training crawls, too large and it blows up.

Why is there a "too large"? Take the simplest valley, L(θ)=h2θ2\loss(\theta)=\tfrac h2\theta^2, where the curvature hh says how sharply it bends. The gradient is hθh\theta, so one step multiplies θ\theta by 1−ηh1-\eta h. If η<1/h\eta<1/h that factor lies between 00 and 11 and θ\theta shrinks smoothly. Between 1/h1/h and 2/h2/h the factor is negative: θ\theta jumps across the minimum but lands closer each time. Beyond 2/h2/h the factor is below −1-1 and every jump overshoots further than the last. In many dimensions the most sharply curved direction sets the limit, η<2/λmax⁡\eta<2/\lambda_{\max}, with λmax⁡\lambda_{\max} the largest curvature, called the sharpness. This is the stability threshold.

Check your understanding

Gradient descent minimizes L(θ)=2θ2\loss(\theta)=2\theta^2, whose curvature is h=4h=4. Which learning rates make it converge?

  1. Any η\eta between 00 and 22
  2. Any η\eta between 00 and 0.250.25; above 0.250.25 it diverges
  3. Any η\eta between 00 and 0.50.5
  4. Any positive η\eta, since every step goes downhill
Show the answer

C. Any η\eta between 00 and 0.50.5

One step multiplies θ\theta by 1−4η1-4\eta, which shrinks it exactly when ∣1−4η∣<1\abs{1-4\eta}<1, that is 0<η<2/h=0.50<\eta<2/h=0.5. Between 0.250.25 and 0.50.5 the iterate hops across the minimum but still closes in.

Mini-batches: cheap, noisy steps

The exact gradient is an average over all nn training examples. For a dataset of a million images, or the trillions of tokens a language model reads, one exact step would cost a full pass over the data. Stochastic gradient descent (SGD) instead estimates the gradient from a small random mini-batch Bt\mathcal B_t of BB examples:

gt=1B∑i∈Bt∇θ ℓ(fθt(xi),yi),θt+1=θt−η gt\mathbf g_t=\frac1B\sum_{i\in\mathcal B_t}\nabla_{\boldsymbol\theta}\,\ell\big(f_{\boldsymbol\theta_t}(\mathbf x_i),y_i\big),\qquad\boldsymbol\theta_{t+1}=\boldsymbol\theta_t-\eta\,\mathbf g_t
On average gt\mathbf g_t equals the true gradient, so SGD heads downhill on average, and the variance of its noise shrinks like 1/B1/B. One pass through the training set, n/Bn/B steps, is an epoch.

Why accept noise? Early in training most examples roughly agree about which way is downhill, so a few hundred of them give a good enough direction at a tiny fraction of the cost. SGD takes thousands of decent steps in the time gradient descent takes one perfect step. The price comes near the bottom. With a constant learning rate the noise never averages away, and the parameters keep jittering around the minimum in a noise ball whose size grows with η\eta and shrinks with BB.

Predict before you look

You raise the batch size from 16 to 256. By what factor does the standard deviation of the gradient noise shrink?

Show the answer

4

The variance falls like 1/B1/B, here by 256/16=16256/16=16, so the standard deviation falls by 16=4\sqrt{16}=4. Sixteen times the computation per step buys four times less noise. That is why batches are not simply made as large as possible: past some size, extra examples per step stop paying for themselves (Gradient Noise, Batch Size & Scaling Rules makes this precise).

Momentum and adaptive steps

Real loss surfaces are full of narrow valleys, steeply curved across and nearly flat along. The steep direction caps the learning rate, so along the floor gradient descent crawls; set η\eta close to the cap and it also zig-zags from wall to wall. Two ideas fix this, and nearly every modern optimizer combines them.

  • Momentum keeps a running velocity, v←βv+gt\mathbf v\leftarrow\beta\mathbf v+\mathbf g_t, and steps along it, θ←θ−ηv\boldsymbol\theta\leftarrow\boldsymbol\theta-\eta\mathbf v, with β\beta around 0.90.9. The back-and-forth across the valley cancels in the running sum, while the steady push along the floor builds up: on a constant slope the step grows to η/(1−β)\eta/(1-\beta), ten times η\eta.
  • Adaptive methods give every parameter its own step size. Adam (Kingma & Ba, 2015) divides each parameter's step by a running root-mean-square of that parameter's recent gradients, so steep and shallow directions move at similar speeds, and it adds momentum on top.
OptimizerWhat it addsTypical use, as of the mid-2020s
SGDthe plain gradient steprarely used without momentum
SGD with momentuma velocity that averages steps over timeconvolutional networks for vision, such as ResNets
Adammomentum plus a step size per parametera robust default in many domains
AdamWAdam with decoupled weight decaythe standard for transformers, including large language models
AdamW (Loshchilov & Hutter, 2019) shrinks the weights directly at every step instead of adding a penalty to the gradient, which Adam's per-parameter rescaling would distort.
Think first Adam keeps two running averages for every parameter. Training a 7-billion-parameter model with AdamW, how much memory do those averages take in 32-bit floating point?

Two numbers per parameter, 1414 billion numbers at 44 bytes each: 5656 GB, twice the 2828 GB of the 32-bit weights themselves. Optimizer state is a large part of the memory bill of training, which is why memory-saving optimizers and schemes that split optimizer states across devices exist.

Schedules: big steps first, small steps last

Two facts shape how the learning rate should change during a run. Early on, large steps make fast progress. Late in the run, the noise ball sets how low the loss can go, and its size grows with η\eta. So practitioners decay the learning rate toward the end of training, following a learning-rate schedule. Most schedules also begin with a short warmup that ramps η\eta up from near zero over the first few hundred or thousand steps, because very large steps at the very start, before the network and the optimizer's running averages have settled, can destabilize training.

ηt=ηmax⁡⋅12(1+cos⁡πtT),t=0,…,T\eta_t=\eta_{\max}\cdot\tfrac12\Big(1+\cos\frac{\pi t}{T}\Big),\qquad t=0,\dots,T
The cosine schedule, after warmup: start at the peak, end at zero, and spend much of the run in between. Other common shapes are step decay (divide η\eta by 10 at fixed epochs), linear decay to zero and warmup–stable–decay, which holds the peak and decays only at the end.
Check your understanding

Late in a run with a constant learning rate, the training loss has stopped improving and only jitters. You cut the learning rate by a factor of 10 and the loss drops sharply within a few hundred steps. What is the best explanation?

  1. The smaller rate let the optimizer escape a bad local minimum
  2. Smaller steps make the gradient larger
  3. The loss was sitting on a noise floor that grows with η\eta, and the smaller rate shrank the noise ball
  4. The network had stopped learning, and changing the rate restarted it
Show the answer

C. The loss was sitting on a noise floor that grows with η\eta, and the smaller rate shrank the noise ball

With a constant rate, gradient noise keeps the parameters bouncing around the bottom of the basin at an excess loss that grows with η\eta (and shrinks with BB). Shrinking η\eta shrinks the bounce, and the loss settles lower. This is the sudden drop seen at every decay point of a step schedule.

What the landscape looks like

The loss as a function of all the parameters is the network's loss landscape. It is not convex, and symmetry alone guarantees that: swap two hidden units, with their incoming and outgoing weights, and you get a different point with exactly the same loss, while the average of the two points is usually worse. For decades this suggested that gradient descent would get stuck in bad local minima. In practice that is rarely what goes wrong, for reasons that are partly understood.

  • Saddles rather than traps. In millions of dimensions, a point that curves upward in every direction is special. Analyses of random high-dimensional functions, backed by experiments, suggest that critical points with high loss are overwhelmingly saddle points, curving up in some directions and down in others (Dauphin et al., 2014). Gradient descent can slow down near a saddle but tends to slide off it.
  • Overparameterization helps. Networks with many more parameters than training examples have enormous, high-dimensional sets of global minima with zero training loss, and gradient descent reliably reaches one of them.
  • Flat and sharp. Minima differ in how steeply the loss rises around them. Gradient descent with learning rate η\eta cannot settle in a minimum sharper than 2/η2/\eta, so large steps steer training toward flatter regions. Whether flatness is also why networks generalize well is debated.

The road ahead

In the Representation lessons each of these ideas gets its own derivation:

  • Mini-Batch SGD & Momentum: why the gradient noise has variance proportional to 1/B1/B, the size of the noise ball, heavy-ball and Nesterov momentum, and how to find a good learning rate.
  • Adaptive Optimizers: RMSProp, Adam & AdamW: per-parameter step sizes, Adam's bias correction and why weight decay must be decoupled from the gradient.
  • Learning-Rate Schedules & Warmup: step, cosine and linear decay, warmup, and why the schedule matters as much as the peak rate.
  • Loss Landscapes: critical points and saddles, visualizing landscapes, lazy versus rich training, sharpness and the stability threshold, and why overparameterized networks are surprisingly easy to train.

The Emergence lessons go to the research frontier: SGD as a stochastic differential equation and the critical batch size, how SGD learns features that kernel methods cannot, sharpness-aware minimization, the competing explanations of why Adam beats SGD on transformers, curvature-aware and orthogonalized optimizers (K-FAC, Shampoo, Muon), schedules that need no fixed horizon, weight averaging, and the geometry of the solutions training finds.

Key takeaways

  • Training minimizes the loss by gradient descent, θ←θ−η∇L\boldsymbol\theta\leftarrow\boldsymbol\theta-\eta\nabla\loss. The learning rate must stay below the stability threshold 2/λmax⁡2/\lambda_{\max} set by the most sharply curved direction.
  • SGD estimates the gradient on mini-batches: unbiased, with noise variance proportional to 1/B1/B. It trades exactness for many cheap steps, and with a constant η\eta it stalls in a noise ball that grows with η\eta.
  • Momentum averages steps so zig-zags cancel and consistent directions speed up; Adam adds a step size per parameter. AdamW is the standard for transformers, and SGD with momentum is still common for convolutional networks.
  • Schedules warm the learning rate up and then decay it: big steps for progress early, small steps late to settle below the noise floor.
  • Deep loss landscapes are nonconvex but rarely trap training: high-loss critical points are mostly saddles, overparameterized networks have vast sets of global minima, and the learning rate itself steers training toward flatter regions.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Your training loss falls for a few steps, then oscillates with growing amplitude and finally becomes NaN. What is the most likely fix?

  1. Use a larger model
  2. Lower the learning rate
  3. Train for more epochs
  4. Raise the learning rate
Show the answer

B. Lower the learning rate

Oscillations that grow are the signature of a step above the stability threshold 2/λmax⁡2/\lambda_{\max}: each step overshoots the valley by more than the last. Lowering η\eta (or adding warmup, if the blow-up comes right at the start) restores stability.

Question 2

Why is deep learning done with mini-batch SGD rather than full-batch gradient descent?

  1. Mini-batch gradients are more accurate than full-batch gradients
  2. Backpropagation cannot compute the full-batch gradient
  3. For the same computation, many cheap noisy steps make more progress than a few exact ones
  4. SGD is guaranteed to find the global minimum, gradient descent is not
Show the answer

C. For the same computation, many cheap noisy steps make more progress than a few exact ones

A mini-batch gradient is unbiased and costs B/nB/n of a full gradient. Early in training its noise barely matters, so SGD makes far more progress per pass over the data. The noise matters only near the end, where decaying the learning rate handles it.

Question 3

On a long, narrow valley, gradient descent zig-zags between the walls while creeping along the floor. What does momentum do about it?

  1. It averages successive steps, so the zig-zags cancel while the consistent push along the floor builds up
  2. It raises the learning rate across the valley and lowers it along the valley
  3. It computes the curvature of the valley and jumps to the bottom
  4. It adds random noise that helps the optimizer leave the valley
Show the answer

A. It averages successive steps, so the zig-zags cancel while the consistent push along the floor builds up

The velocity v←βv+g\mathbf v\leftarrow\beta\mathbf v+\mathbf g sums recent gradients. Components that flip sign from step to step cancel, components that keep their sign accumulate up to a factor 1/(1−β)1/(1-\beta). Per-direction step sizes are what adaptive methods such as Adam add.

Question 4

SGD runs with a constant learning rate η\eta and batch size BB. What happens to the training loss late in training?

  1. It converges exactly to the minimum, only more slowly than gradient descent
  2. It hovers above the minimum at a level that grows with η\eta and falls with BB, until the learning rate is decayed
  3. It slowly rises again, because the noise accumulates without bound
  4. It hovers at a level that depends only on the batch size
Show the answer

B. It hovers above the minimum at a level that grows with η\eta and falls with BB, until the learning rate is decayed

Each step adds fresh noise of size proportional to η\eta, while the pull toward the minimum removes a fraction of the error. The two balance in a noise ball whose excess loss grows with η\eta and shrinks with BB. Decaying η\eta is what lets SGD settle lower.

Question 5

Which statement about the loss landscapes of deep networks is best supported?

  1. They are convex, so every minimum is a global minimum
  2. Gradient descent usually gets trapped in poor local minima, so many random restarts are standard practice
  3. Every minimum is equally flat, so the learning rate cannot affect which one is found
  4. They are nonconvex, but high-loss critical points tend to be saddles, and overparameterized networks have vast sets of global minima that gradient descent reaches
Show the answer

D. They are nonconvex, but high-loss critical points tend to be saddles, and overparameterized networks have vast sets of global minima that gradient descent reaches

Permutation symmetry alone makes the loss nonconvex. Yet poor local minima are rarely the obstacle in practice: high-loss critical points are mostly saddles, and with enough parameters zero training loss is reachable from almost any start. Minima do differ in sharpness, and the learning rate influences which kind is found.

Go deeper

Further reading

  • I. Goodfellow, Y. Bengio & A. Courville, Deep Learning, ch. 8 "Optimization for Training Deep Models" (MIT Press, 2016), free at deeplearningbook.org.
  • L. Bottou, F. E. Curtis & J. Nocedal, "Optimization methods for large-scale machine learning," SIAM Review 60(2), 223–311 (2018).
  • D. P. Kingma & J. Ba, "Adam: A method for stochastic optimization," ICLR (2015).