Gradient Descent
Gradient descent turns the local geometry of a differentiable loss surface into an iterative algorithm: move opposite the steepest local direction, with a step size justified by a first-order Taylor model.
1. Concept overview
Gradient descent is an iterative optimization algorithm for minimizing a differentiable objective . Starting from an initial point , it repeatedly applies
where is the gradient and is the learning rate. It is the single most important algorithmic primitive in modern AI: every trained neural network is, at its core, some variant of this recurrence applied to a very high-dimensional loss function.
What makes the update more than a heuristic is the Taylor model: near ,
Among all unit-cost directions, the one that decreases this linear model fastest is . Gradient descent takes that direction, scaled by .
2. Why this concept exists
Most interesting objectives in machine learning cannot be minimized in closed form. For linear regression there is the normal equation , but it requires forming and inverting a matrix ( time, memory) and fails when is singular. For a neural network there is no closed form at all.
Earlier approaches:
- Analytic stationary-point solving: set and solve. Works for a handful of textbook problems; impossible for nonlinear systems with millions of variables.
- Coordinate descent / grid search: optimize one coordinate at a time or enumerate candidates. Suffers the curse of dimensionality.
- Finite-difference search: perturb each coordinate, measure the change. Costs function evaluations per step.
Gradient descent uses analytic derivatives obtained by backpropagation or automatic differentiation: one forward and one backward pass gives all partial derivatives at roughly the cost of one forward pass. That is the reason deep learning became practical.
3. Historical background
The method is usually credited to Cauchy (1847), who proposed it for solving systems of equations and explicitly used the phrase "la méthode de la descente la plus rapide". Robbins and Monro (1951) introduced stochastic approximation, the statistical ancestor of stochastic gradient descent. In machine learning, Widrow and Hoff (1960) used gradient-based adaptation in the ADALINE perceptron; Rumelhart, Hinton and Williams (1986) combined backpropagation with gradient descent and made multilayer training practical. Bottou (1991) and subsequent work established the stochastic optimization theory used for large-scale learning. Bottou, Curtis and Nocedal (2018) give the modern viewpoint: optimization methods for learning differ from classical numerical optimization because the objective is an expectation and accuracy is limited by statistical error.
4. Fundamental problem
Given access to and (approximately) , find without solving a global system of equations, using a number of gradient evaluations that is affordable when is enormous.
Three obstacles make this non-trivial:
- Locality: the gradient describes only an infinitesimal neighborhood; a finite step can overshoot or diverge.
- Geometry: curvature varies across directions. A single scalar step size cannot be ideal for all of them.
- Stochasticity: in learning we usually see for one sample or minibatch, an unbiased but noisy estimate.
5. First-principles explanation
Start from two facts.
Fact 1 (directional derivative). For a unit vector ,
By Cauchy–Schwarz, , with equality at . So the steepest descent direction in Euclidean geometry is exactly the negative gradient.
Fact 2 (linear approximation). Taylor's theorem with remainder gives
for some . The first-order term predicts decrease for a step ; the quadratic remainder limits how large may safely be. If the objective is -smooth (), the descent lemma guarantees
so any strictly decreases whenever the gradient is nonzero. This single inequality is the rigorous core of the method.
6. Prerequisite concepts
You need: (a) partial derivatives and the gradient as the vector of partials; (b) directional derivatives and the inner-product identity above; (c) Taylor expansion with remainder, to justify the local linear model; (d) Cauchy–Schwarz; (e) convexity and the notion of -smoothness for convergence statements; (f) basic numerical linear algebra to understand why forming normal equations is expensive. See the linked concepts for each.
7. Complete mathematical formulation
Setup. differentiable, -smooth, possibly convex.
Update.
Stochastic version. With loss and minibatch ,
Assumptions used in analysis.
- (A1) Lower bounded: .
- (A2) -smooth: .
- (A3) For convex rates: convex and .
- (A4) For stochastic rates: (bounded variance) or interpolation/strong-growth conditions.
Notation dictionary. See section 8; all symbols are defined there before use.
8. Notation dictionary
| Symbol | Meaning | Type | |---|---|---| | | parameters (point in weight space) | vector | | | objective / loss | scalar | | | gradient, vector of partial derivatives | vector in | | | learning rate at step | scalar | | | (possibly stochastic) gradient estimate | vector | | | Lipschitz constant of ; curvature upper bound | scalar | | | strong-convexity parameter () | scalar | | | initial distance to optimum | scalar | | | a data sample | random variable | | | per-sample loss | scalar | | | iteration index | integer | | | total number of iterations | integer | | | Euclidean inner product | bilinear form | | | Euclidean () norm | norm | | | Loewner order on symmetric matrices | relation |
9. Step-by-step derivation
Step 1 — choose a local model. For a small displacement , Taylor's theorem gives .
Step 2 — choose a step budget. Without curvature information, constrain . Solve
By Cauchy–Schwarz the minimizer is .
Step 3 — absorb normalization into the step size. Define , giving . The normalization is redundant because is tuned anyway.
Step 4 — enforce sufficient decrease. Using -smoothness (a.k.a. the descent lemma):
Substitute :
The right-hand side decreases iff ; the coefficient is maximized at .
Step 5 — telescope. Sum over with :
hence . This is a stationarity guarantee, not necessarily global optimality when is nonconvex.
Step 6 — convex and strongly convex refinements. For convex with , standard arguments yield for the averaged iterate. For -strongly convex , : linear convergence with condition number .
10. Proofs and proof intuition
Lemma (descent lemma). If is -smooth then for all , Proof. Define . Then and . Integrating from to : .
Theorem (stationarity). Under A1–A2, constant , . Proof. Rearrange the descent inequality to . Sum and telescope; divide by .
Proof intuition. Every step spends part of the available loss decrease. The total budget is finite, so the average squared gradient must shrink like .
Strong-convexity sketch. For -strongly convex , ; the geometry is a ball contracting toward the unique optimum at a rate governed by .
11. Geometric interpretation
Imagine the loss as a landscape. The gradient at a point is a vector perpendicular to the level set passing through that point, pointing uphill. Negative gradient is the normal to the contour pointing downhill. Taking a step of length along this normal is the Euclidean-steepest way to leave the current contour.
For a quadratic with eigenvalues , the contours are ellipses. Gradient steps zig-zag because the gradient is normal to elongated ellipses rather than pointing at the center. Stable steps require . At the optimal constant step the error contracts by per step, where ; other step sizes converge more slowly. Geometry, not just "slope", controls speed.
12. Visual explanation
Use the interactive Gradient Descent Playground in the Practical Labs section. It plots contours of a user-selected surface (quadratic bowl, Rosenbrock, saddle) and the trajectory of the iterate. Toggle: (i) step size — watch divergence above ; (ii) momentum — watch the zig-zag damp; (iii) conditioning — stretch the ellipse and observe the slowdown. The plotted quantity should match the theoretical envelope on convex surfaces. The visualizer displays the current , , and so you can connect geometry to the update equation.
13. Numerical worked example
Minimize ; here , , .
Start , .
- : . , .
- : , , .
- : , .
The component converges at rate , the component at : after 10 steps is essentially optimal while is still far away. This is the conditioning effect: a single scalar step size is forced to be small by the steep direction, slowing the flat direction.
If instead , the coordinate multiplies by each step and diverges geometrically.
14. Real-world analogy
A hiker in fog wants to reach the lowest point of a valley. They can feel the local slope under their feet but cannot see the whole landscape. The rational policy: face downhill along the steepest local slope and take a careful step. A long step (large ) can overshoot into a higher region; a tiny step wastes time. A topographical map with tightly spaced contours is a high-curvature direction; widely spaced contours are flat. The hiker's zig-zag in an elongated valley mirrors gradient descent on an ill-conditioned quadratic.
15. Algorithm pseudocode
algorithm GradientDescent(f, grad_f, theta_0, eta, T, tolerance):
theta <- theta_0
for t = 0 .. T-1:
g <- grad_f(theta) # analytic / autodiff, O(cost of f)
if norm(g) < tolerance: break # first-order stationarity
theta <- theta - eta * g # the update
if verbose: log(f(theta), norm(g))
return theta
# Stochastic variant: replace g by mean grad_f_i over minibatch B_t;
# optionally decay eta_t.
16. Implementation from scratch
import numpy as np
def gradient_descent(f, grad, theta0, lr=0.05, n_steps=200, tol=1e-10):
"""Minimise f by vanilla gradient descent. Pure NumPy, no autodiff."""
theta = np.array(theta0, dtype=float).copy()
history = []
for t in range(n_steps):
g = grad(theta)
history.append((t, f(theta), np.linalg.norm(g)))
if np.linalg.norm(g) < tol:
break
theta -= lr * g
return theta, history
# Worked quadratic: f = 0.5 x^2 + 5 y^2 => grad = (x, 10y)
f = lambda w: 0.5*w[0]**2 + 5*w[1]**2
grad = lambda w: np.array([w[0], 10*w[1]])
theta, hist = gradient_descent(f, grad, [10.0, 10.0], lr=0.05, n_steps=200)
assert np.allclose(theta, [0, 0], atol=1e-3), theta
print(theta, hist[0], hist[-1])
17. Professional library implementation
import torch
# Autodiff removes the need to hand-derive grad for every model.
w = torch.tensor([10.0, 10.0], requires_grad=True)
opt = torch.optim.SGD([w], lr=0.05) # production optimizer = same recurrence
for t in range(200):
loss = 0.5*w[0]**2 + 5*w[1]**2
opt.zero_grad(set_to_none=True) # avoid accumulating stale gradients
loss.backward() # fills w.grad
opt.step() # w <- w - lr * w.grad
print(w.detach())
For large models use torch.optim.AdamW (section on AdamW) and wrap the loop in torch.cuda.amp.autocast for mixed precision. The recurrence is unchanged; only the preconditioner and dtype change.
18. Code walkthrough
Scratch version. grad(theta) returns the analytic gradient. theta -= lr * g is an in-place update; copying theta0 avoids mutating the caller's array. The history tuple records loss and gradient norm so you can verify the theoretical decrease inequality numerically.
PyTorch version. requires_grad=True builds a dynamic computational graph during the forward pass. loss.backward() applies the chain rule in reverse topological order (backpropagation), accumulating into .grad. zero_grad(set_to_none=True) clears buffers before the next backward, because PyTorch accumulates gradients by default — this is the most common bug in hand-written training loops. opt.step() performs the update. Nothing in the loop is specific to this quadratic: replace loss by any differentiable model output.
19. Tensor and memory analysis
For a parameter tensor of shape ( elements) in fp32 you need:
- parameters: bytes;
- gradient buffer: bytes;
- optimizer state: for SGD, for Adam (two moment estimates);
- activations: depends on the forward graph, often per layer times batch size.
A full update touches parameters and gradients at least twice (read in the step, write back). On a GPU this is memory-bandwidth bound: with bandwidth bytes/s, the minimum step time is roughly for SGD. For a 7B-parameter model in fp32, weights and gradients alone occupy bytes GB, and a full update reads and writes most of that traffic per step. This is why mixed precision and fused optimizers matter.
20. Time complexity
Per iteration: for a full-batch gradient (finite differences would be ). With iterations, . Minibatch of size costs and gives an unbiased gradient with variance , so there is a trade-off between per-step cost and gradient quality. Convergence iterations: to reach in the nonconvex smooth case; for convex function-value suboptimality; when strongly convex.
21. Space complexity
Parameters plus a gradient buffer , both required by any first-order method. SGD adds no optimizer state beyond that gradient buffer; Adam adds two moment buffers, . Backpropagation storage is , which can be reduced to with checkpointing at the cost of extra forward recomputation.
22. Experimental demonstration
Run the scratch implementation on with and record: number of steps to , final error, and whether the trajectory diverged. Expected (gradient norm ): takes about 916 steps, about 180, oscillates but converges, diverges. Then repeat on the Rosenbrock function ; you will see that curvature variation produces a long curved valley and slow progress — motivating momentum and adaptive methods. Plot vs ; the slope should match theory on the quadratic.
23. Benchmark results
Do not trust universal speed claims. On the quadratic above, gradient descent with reaches gradient norm in about 88 steps; Newton's method reaches machine precision in 1 step because the Hessian is constant. On logistic regression on a moderately conditioned dataset, gradient descent and L-BFGS are competitive; on ill-conditioned deep-network objectives, SGD+momentum and AdamW are the practical defaults. Always report the conditioning of your problem, the step-size rule, and the metric (gradient norm vs. function gap vs. test accuracy). There is no legitimate single number that ranks optimizers across all problems.
24. Limitations
- Requires differentiable objectives (or a surrogate); nonsmooth terms need subgradients or proximal steps.
- A single global scalar step size ignores anisotropic curvature.
- Sensitive to feature scaling: unnormalized features produce ill-conditioned geometry.
- In nonconvex problems it converges only to a stationary point, which may be a saddle or a poor local minimum.
- Stochastic noise prevents exact convergence with constant step size; decay is needed.
- Can be trapped in flat regions where gradients are nearly zero.
- Very large batches lose the implicit regularization and noise benefits of SGD.
25. Failure scenarios
- Divergence: . On the quadratic, grows by factor .
- Vanishing gradients: saturated sigmoid/tanh layers produce gradients near zero; training stalls. Fixed by initialization, normalization, ReLU-family activations, residuals.
- Exploding gradients: recurrent networks multiply Jacobians over time; clip the global norm.
- Saddle trapping: at a saddle , descent stops even though better points exist; stochastic noise and momentum help escape.
- Bad scaling: features on wildly different scales create elongated contours; standardize inputs.
- Accumulated gradients in PyTorch: forgetting
zero_grad()adds old gradients to new ones and corrupts the update.
26. Common misconceptions
- "Gradient descent always finds the global minimum." False: only guaranteed for convex ; nonconvex objectives have many stationary points.
- "The gradient points to the minimum." It points to steepest local ascent in Euclidean geometry, not toward the global optimum.
- "Smaller learning rate is always safer." It is safer but slower; is the standard choice that guarantees the descent-lemma bound, not the optimal step. For a quadratic with eigenvalues in the optimal constant step is .
- "More iterations always improve test accuracy." Training loss may fall while generalization degrades; monitor validation metrics.
- "Stochastic gradient is a worse gradient." It is unbiased; its noise is often beneficial for escaping sharp minima.
- "Gradient descent is the same as backpropagation." Backprop computes the gradient; gradient descent uses it to update weights.
27. Alternative approaches
- Momentum / Nesterov acceleration: accumulate past gradients to smooth noisy directions and accelerate flat ones.
- Adaptive methods (AdaGrad, RMSProp, Adam/AdamW): per-coordinate preconditioning.
- Second-order (Newton, quasi-Newton L-BFGS, natural gradient): use curvature, faster per-iteration but storage or approximations.
- Coordinate descent: useful for sparse/separable objectives.
- Derivative-free (CMA-ES, evolution strategies, SPSA): when gradients are unavailable or non-differentiable.
- Conjugate gradient: efficient for large linear systems and quadratics.
29. Research applications
- Optimization theory: sharper convergence bounds under relaxed smoothness, interpolation, and heavy-tailed noise.
- Deep learning: understanding why SGD finds generalizing minima; implicit bias and sharpness-aware minimization.
- LLM training: step-size scheduling, warmup, gradient clipping, and loss-spike mitigation at scale.
- Federated / distributed optimization: averaging, communication compression, local SGD.
- Meta-learning: learned optimizers that emit updates.
- Scientific ML: physics-informed losses with stiff, ill-conditioned landscapes.
30. Important research papers
- Cauchy A. L. (1847), Méthode générale pour la résolution des systèmes d'équations simultanées, C. R. Acad. Sci. Paris — original steepest descent.
- Robbins H., Monro S. (1951), A Stochastic Approximation Method, Annals of Mathematical Statistics — foundation of SGD.
- Rumelhart D., Hinton G., Williams R. (1986), Learning representations by back-propagating errors, Nature — backprop + gradient-based training.
- Bottou L. (1991), Stochastic gradient learning in neural networks, Neuro-Nîmes.
- Bottou L., Curtis F. E., Nocedal J. (2018), Optimization methods for large-scale machine learning, SIAM Review. DOI: 10.1137/16M1080173.
- Nesterov Y. (1983/2004), Introductory Lectures on Convex Optimization — rates and acceleration.
31. Further reading
- Boyd & Vandenberghe, Convex Optimization (2004), chapters 9–10 — free PDF at stanford.edu/~boyd/cvxbook.
- Nocedal & Wright, Numerical Optimization (2nd ed., 2006), chapters 2–3.
- Bottou et al. (2018), SIAM Review 60(2):223–311.
- Stanford CS231n notes on optimization: cs231n.github.io/optimization-1/.
- PyTorch documentation: torch.optim — docs.pytorch.org/docs/stable/optim.html.
32. Practical exercises
- Implement
gradient_descentabove from memory; verify it on the quadratic to . - Derive the gradient of and implement GD; compare with the closed-form ridge solution.
- Plot the trajectory for ; identify the divergence threshold empirically and compare with .
- Reimplement the update with finite differences () and compare accuracy and runtime.
- Run on Rosenbrock from three starting points; report steps to convergence or failure.
33. Debugging challenges
- Your loss increases every step. Check the sign of the update and whether .
- Loss decreases then explodes after step 200. Look for numerical overflow or a learning rate schedule that increased .
- PyTorch loss will not decrease. Did you call
zero_grad()? Are parameters on the same device as data? Isrequires_grad=True? - Gradient norm is exactly zero. Check for saturated activations, detached tensors, or a constant loss.
- GPU is slower than CPU. Small tensors are launch-bound; batch operations or use fused kernels.
34. Advanced exercises
- Prove the convex rate for the averaged iterate yourself.
- Implement gradient descent with backtracking Armijo line search and verify the sufficient-decrease condition.
- Implement a preconditioned update ; study on the quadratic and relate to condition number.
- Reproduce a loss spike in a small transformer training run and diagnose it via gradient-norm logging.
- Derive and implement the natural-gradient step for a Bernoulli model; compare to ordinary GD in parameter space.
35. Interview questions
- Derive the step-size bound from the descent lemma.
- Why does a large condition number slow gradient descent? Give the exact rate for a quadratic.
- Distinguish SGD, minibatch GD and full-batch GD in terms of bias, variance and cost.
- Why do we decay the learning rate? What goes wrong with a constant rate under noisy gradients?
- Prove that the negative gradient is the steepest descent direction under the Euclidean norm. Under what norm is it not?
- When would you prefer L-BFGS over Adam?
36. Research questions
- Can we certify convergence under relaxed smoothness without knowing a priori?
- How does gradient noise covariance affect the implicit bias toward flat minima?
- What is the exact role of learning-rate decay in generalization for overparameterized models?
- Can learned preconditioners beat AdamW consistently across architectures, and how should this be evaluated fairly?
- How do we design step-size rules for objectives with heavy-tailed gradient noise?
37. Mastery assessment
To pass: (1) derive the update from a first-order Taylor model and Cauchy–Schwarz without notes; (2) prove the descent inequality and the bound; (3) implement GD from scratch and verify the quadratic example numerically; (4) explain divergence, saddle trapping and conditioning with concrete examples; (5) answer the interview questions above. Complete the linked assessment in the Assessments section, which mixes derivation, numerical and debugging items. Self-reporting a read is not mastery.
38. Implementation submission
Push a repository containing: gd.py (scratch implementation), experiments.ipynb (the four step-size runs and Rosenbrock), a README.md with derivations and observed vs. theoretical rates, and a test file asserting convergence on the quadratic and divergence for . Include a plot of and a short note on which assumptions held. Submit the repository URL and the exact command to reproduce your results.
39. Completion criteria
All of: every section of this page read and the derivation reproduced on paper; scratch implementation passing tests; three experiments with recorded numbers and plots; assessment score at least 80%; one failure case reproduced and explained; research question answered with a one-page note citing at least one paper. Only then may the concept be marked mastered in the task system.`