Gradient Descent & SGD
Training is descent on the empirical risk: step the parameters against the gradient. We derive the minibatch gradient as an unbiased estimator whose variance falls as , derive the learning-rate ceiling from the smoothness-stability bound , and lay out the schedules (step, exponential, cosine, warmup) that anneal it over training.
╌╌╌╌
Every deep network is trained by the same move from the training loop: compute the gradient of the loss with respect to the parameters, then step the parameters in the opposite direction. With the full parameter vector and the loss, gradient descent is the iteration
where is the learning rate. The gradient points in the direction of steepest ascent, so its negation is the locally steepest descent; sets how far we trust that local direction before recomputing it.1
One step is a small dataflow: read the current parameters, evaluate the gradient there, scale it by the rate, and subtract to produce the next parameters. That loop repeats until the gradient is (near) zero.
What we actually minimize
The object we want to minimize is the risk, the expected loss over the true data distribution ; what we can compute is the empirical risk, its average over the finite training set :
The exact gradient is a sum over all examples, so one true gradient step costs a full pass over the data. For in the millions that is too expensive per update, and it is also wasteful, because the examples are redundant and an estimate of the gradient from a small sample already points the right way.2
Three granularities of the gradient
The gradient is a sample mean, so we may estimate it from all examples, from one, or from a minibatch of drawn at random. These are the three canonical variants; they trade computation per step against the noise in the direction they produce.
| variant | gradient estimate | cost / step | noise | use |
|---|---|---|---|---|
| batch GD | none (exact) | small data, convex problems | ||
| minibatch SGD | the default for deep nets | |||
| (pure) SGD | , one example | high | online / streaming data |
Pure SGD () and full-batch GD () are the endpoints of one dial; the practical regime is the middle, on the order of to , large enough to use vectorized hardware and damp the noise, small enough that each step is cheap and the steps are frequent.3
The minibatch gradient is unbiased
Why is it legitimate to step against a gradient computed from a handful of examples? Because that estimate is unbiased: in expectation it equals the true gradient. Let with , where the indices in are drawn uniformly. Each draw has , so by linearity of expectation,
The estimate is centered on the truth at every batch size; what controls is not the center but the spread.
Variance falls as
Model the per-example gradients as i.i.d. draws with common covariance . The minibatch gradient is their average, so its covariance shrinks linearly in . Writing for the deviation, with independence across the draws,
Taking the trace gives the total variance of the estimate, and the typical magnitude of the gradient noise is its square root:
This is the speed–noise tradeoff in one line. The catch is the square root: halving the noise costs a larger batch (and the compute per step). Past a point the variance reduction is not worth the cost — large batches give precise but expensive steps, and the noise they remove was partly useful, helping the iterate escape sharp minima and saddle regions.4
For example, suppose in some unit, so the mean-squared error of the estimate is and the noise scale (its square root) is . Then:
| batch | MSE | noise scale | compute / step |
|---|---|---|---|
Each row costs the compute of the one above for exactly a cut in noise. Going from to is the work for an tighter estimate. The practical batch size is the one that just saturates the vectorized hardware; beyond that the marginal precision is not worth the compute, and the residual noise aids exploration anyway.
The same tradeoff shows in the descent path. Full-batch GD takes the exact gradient and traces a smooth curve to the minimum; SGD steps along a noisy estimate and drifts toward it, the trajectory jittering but still trending downhill because the noise has zero mean.
Convergence and the learning rate
The learning rate is the single most important hyperparameter, and its safe range is governed by the curvature of the loss. Assume is -smooth: its gradient is -Lipschitz, , which bounds how fast the gradient can change. Smoothness gives the descent lemma, a quadratic upper bound on the loss after a step:
Substitute the GD update and abbreviate :
The loss is guaranteed to decrease whenever the bracket is positive, i.e. . This is the stability bound on the step size.
The optimal step within this bound is . The guaranteed decrease is ; treating the coefficient as a function of and setting gives , at which . Substituting back, , the largest per-step drop the bound allows. For a -strongly-convex, -smooth loss, the iterates converge linearly at a rate set by the condition number :
A well-conditioned loss () converges in a few steps; an ill-conditioned one () converges slowly, because the largest stable is capped by the steepest direction () while progress along the shallow direction is limited by .
The factor per step is what makes this quantitative. To cut the distance to the optimum by a factor of takes steps with , i.e. . So the iteration count scales linearly in the condition number:
| condition number | per-step factor | steps for progress |
|---|---|---|
A quadratic bowl with axes in a ratio () needs on the order of full-batch steps for each decimal digit of accuracy, and deep-network losses routinely have curvature ratios far larger than that. This linear-in- cost is the concrete reason ill-conditioning hurts, and it motivates every preconditioning trick in the next lesson. The three regimes of are visible directly in the loss curve.
| learning rate | behavior | cause |
|---|---|---|
| too small () | loss falls, but slowly | each step trusts the gradient too little |
| well-tuned () | fast, monotone descent | near-maximal stable step |
| too large () | oscillation, then divergence | quadratic overshoots; bound violated |
Learning-rate schedules
A single fixed is a compromise: large early progress wants a big rate, fine late-stage convergence wants a small one. For SGD specifically, a constant rate cannot converge to the exact minimum. Near the true gradient is small, but the stochastic gradient still carries noise of scale ; the update then injects a random kick of size every step, and the iterate settles into a stationary cloud of radius around rather than the point itself. Shrink and the cloud shrinks with it, but only a rate that decays to zero drives the residual error to zero. So must decay. A schedule does this: start large, shrink over training. The Robbins–Monro conditions (steps sum to infinity, so any starting point is reachable) and (the injected noise is summable, so the cloud collapses) are the classical guarantee that decaying SGD reaches the minimum. A schedule like satisfies both; a constant satisfies the first but violates the second, and so it stalls in the noise ball.
| schedule | formula | shape | notes |
|---|---|---|---|
| step decay | staircase | drop by factor every steps | |
| exponential | smooth decay | continuous analogue of step decay | |
| cosine annealing | half-cosine | smooth to at horizon | |
| linear warmup | for | ramp up | then hand off to a decay schedule |
Warmup ramps up from near zero over the first steps before any decay begins — the early iterates are far from a good region and the gradient estimates are noisiest there, so a small initial rate prevents the first few steps from blowing up; it is near-standard for large-batch and transformer training. In practice warmup is composed with cosine: ramp up, then anneal down.5
The algorithm
Assembling the pieces (sample a minibatch, average its gradient, look up the scheduled rate, step) gives the standard training algorithm of deep learning.
- 1initialize (random init)
- 2for to do
- 3sample a minibatch of sizeuniform, without replacement
- 4unbiased estimate
- 5step / cosine / warmup
- 6descent step
- 7return
One pass over the whole dataset is an epoch ( steps); training runs for many epochs, reshuffling the data each time so successive minibatches are fresh draws. Every line here is the target of a later refinement.6
A worked SGD step, end to end
For a worked example, run one minibatch step of the algorithm on the smallest model that has a gradient: linear regression, with the squared loss . The parameters are , and the per-example gradients are and .
Start from , , take a minibatch of examples and , and use . First the forward pass and residuals:
Each example contributes a gradient ; the minibatch gradient is their average:
The residuals are negative (the model underpredicts), so the gradient is negative, and the descent step moves both parameters up:
One step lifted from toward the least-squares slope. Re-running the forward pass with the new parameters shows the loss fell: the residual on the first example shrinks from to , and on the second from to . The batch mean-squared residual dropped from to in a single update. Iterating this loop is training; the only thing a deep network changes is that now flows through backpropagation rather than a one-line derivative.
The ravine: why plain SGD struggles
The stability bound exposes plain GD's weakness. When the loss is ill-conditioned (curvature far steeper in one direction than another, ), the largest stable is fixed by the steep direction, but that same makes almost no progress along the shallow one. The result is a ravine: the iterate bounces back and forth across the steep walls while creeping slowly down the gentle floor toward the minimum.
Halving to stop the zig-zag also halves progress along the floor: the ratio of progress to oscillation is fixed at , and no scalar changes it. To address this, change the direction of the step rather than its length: damp the oscillating component and accumulate the consistent one. This is the move momentum and adaptive methods make, in the next lesson.
Learning-rate methods
The standard references treat the learning rate as a hyperparameter to tune by hand; the research literature has since turned each of this lesson's knobs into a method.
- Finding without a grid search. Smith's LR range test sweeps the learning rate up exponentially over a few hundred iterations and plots loss against rate; the largest rate before the loss turns up is a near-optimal choice, read straight off the curve. It replaces the smoothness constant (which we never know) with a direct measurement.7
- Batch size as a substitute for decay. The noise law says a larger batch is a quieter gradient, and Smith et al. showed the two levers are interchangeable: increasing the batch size over training reaches the same accuracy as decaying the learning rate, while keeping the step count low enough to parallelize. The noise-ball argument of the schedules section is exactly why.8
- Large-batch training at scale. Goyal et al. trained ImageNet in one hour by pushing the batch to with the linear scaling rule (scale in proportion to ) plus a warmup ramp — the same warmup this lesson motivated from noisy early gradients, now standard for the largest models.9
- One-cycle and super-convergence. Smith's one-cycle policy ramps the rate
up to a large peak and back down within a single run, and can train some
networks an order of magnitude faster (
super-convergence
), a schedule that goes well past the standard monotone-decay picture.10
Each of these is a public, named result that builds directly on the two facts this lesson derived: the noise law and the stability bound.
Takeaways
- Training is the iteration : step the parameters against the gradient of the empirical risk.
- The gradient is a sample mean, so it can be estimated from a minibatch of examples, an unbiased estimator () whose variance is , noise magnitude . Bigger batches give precise, expensive steps; the useful regime is the middle.
- For an -smooth loss, GD decreases the loss iff ; the optimal step is , and convergence rate is set by the condition number. Too small slow; too large diverge.
- A fixed rate cannot converge under SGD noise; schedules (step, exponential, cosine annealing, linear warmup) decay over training to trade fast early progress for fine late convergence.
- Plain SGD zig-zags in ill-conditioned ravines because one must serve both the steep and shallow directions — the motivation for momentum.11
Footnotes
- Goodfellow, Deep Learning, §4.3 — Gradient-Based Optimization: the negative gradient as the direction of steepest descent and the role of the step size. ↩
- Goodfellow, Deep Learning, §8.1 — How Learning Differs from Pure Optimization: minimizing empirical risk as a surrogate for the inaccessible risk over . ↩
- Goodfellow, Deep Learning, §8.1.3 — Batch and Minibatch Algorithms: why minibatches of – trade statistical efficiency against hardware throughput. ↩
- Goodfellow, Deep Learning, §8.1.3 — diminishing returns of larger batches (noise falls only as ) and the regularizing value of gradient noise. ↩
- Chollet, Deep Learning with Python, §2.4 — The Engine of Neural Networks: gradient-based optimization, the learning-rate knob, and schedule/warmup heuristics in practice. ↩
- Stevens, Deep Learning with PyTorch, Ch. 5 — The Mechanics of Learning: the minibatch loop, epochs, and reshuffling as implemented in a training routine. ↩
- Smith, Cyclical Learning Rates for Training Neural Networks, WACV 2017 — the learning-rate range test: sweep upward and read the largest stable rate off the loss curve. ↩
- Smith, Kindermans, Ying & Le, Don't Decay the Learning Rate, Increase the Batch Size, ICLR 2018 — growing is equivalent to decaying , since both shrink the gradient noise. ↩
- Goyal et al., Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour, 2017 — the linear scaling rule () plus a warmup ramp for very large batches. ↩
- Smith & Topin, Super-Convergence: Very Fast Training of Neural Networks Using Large Learning Rates, 2018 — the one-cycle policy (ramp up to a large peak, then down) and super-convergence. ↩
- Goodfellow, Deep Learning, §8.2 — Challenges in Neural Network Optimization: ill-conditioning of the Hessian and the zig-zag of first-order descent in a ravine. ↩
╌╌ END ╌╌