Unit 6 of 6 · about 3 hours · derive, implement
Backpropagation through dense layers and gradient checks
Backprop hides a sign, transpose or accumulation bug in every new layer. A two-evaluation directional check finds it in seconds; a per-coordinate loop costs evaluations.
You'll be able to
- Derive backprop through an affine map, an elementwise nonlinearity and a branched sum, with shapes stated.
- Implement centered-difference gradient checks including random-direction tests for matrix parameters, with tolerance and norm stated.
- Diagnose step-size, cancellation, nondifferentiability and stochastic-state failures from the error curve.
Covers
Read
In this order, only the parts listed
0 of 4 done
- Finite-difference approximations and their errorsMIT 18.S096 - Matrix Calculus for ML
Lecture 3, Part 2 notes (course notes Chapter 4): forward differences and first-order truncation error (Sections 4.2-4.5), roundoff and the step-size rule of thumb (Section 4.6), centered differences and Richardson extrapolation (Section 4.7)
- Numeric differentiation and the reverse engineHands-On ML - Autodiff notebook
Cells Numeric differentiation (
gradients()takes one-sided differences witheps = 1e-4and calls; nesting it gives a Hessian whose exact 0 entry prints as -1.4e-6) and Reverse mode autodiff (hand engine withbackpropagate, the artifact to test against differences) - Backprop equations with parent accumulationMathematics for Machine Learning - Ch. 5
Section 5.6 (pp. 160-164): backward computation working from the output with accumulation over parent nodes (5.135)-(5.145); the dense-layer backward pattern
- Reverse mode on computational graphsMIT 18.S096 - Matrix Calculus for ML
Lecture 5, Part 3 notes (course notes Chapter 8, Section 8.3): computational graphs, summing products along every input-to-output path, and reverse mode on graphs (Section 8.3.1)
Focus on
- Centered differences carry error until rounding at about takes over; in
float64sits near the bottom of that U-curve. - The random-direction test against the directional difference needs 2 evaluations for any shape and catches transpose and scale bugs. Use several seeded .
- Backprop through a branch sums cotangents from every downstream use. A missing accumulation is the classic silent bug.
- Relative error needs a scale: use so near-zero gradients do not explode the ratio.
Common mistakes · 3
- Checking at one far from without a sweep. For the
tanhlayer in Reproduce, leaves 4.3e-3 relative error and hides real bugs above the truncation floor, while drowns in cancellation. - Gradchecking through a kink or a stochastic op and reading the mismatch as a backprop bug. Freeze stochasticity and keep nondifferentiable points out of the check.
- Comparing with
==or to too many digits. State the norm and tolerance; for thetanhlayer,float64centered differences bottom out near 1e-10, not 1e-16.
Try it yourself
Closed-book, before checking anything
standard_normal from numpy.random.default_rng(5) in float64: , . Measured: = 1.73395370, centered differences () give relative error = 3.4e-11, and the direction test = 1.4e-10. Repeat at to get relative error 4.3e-3, consistent with truncation.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Write the backward pass for , , , with shapes.Answer
, shape . (), , . The outer product, not an inner product, gives .
2.Why is centered while one-sided is ?Answer
Taylor expansion: the forward difference leaves a first-order term , while centering cancels all odd powers of , leaving . The remainder form needs .
3. has 6 entries. Compare per-coordinate and directional check cost.Answer
Per-coordinate costs 12 evaluations; one direction costs 2. Run 3 to 5 random directions from a seeded generator and record the seed,
dtypeand norm.4.The check disagrees only at entries whose pre-activation sits near zero under ReLU. Is backprop wrong?Answer
Probably not. Centered differences average left and right slopes at a nondifferentiable kink. Move the check point or use a smooth activation for the check.
Practice
- Deep-ML 313: Numerical Gradient Checking
Implement
numerical_gradient_check(f, x, analytical_grad, epsilon)with centered differences; tests check quadratics againstrel_err < 1e-5The signature defaults
epsilonto 1e-7. Sweep , explain why 1e-5 is safer infloat64, then keep your dense-layer check from Reproduce as the oracle the section mini-project extends with a seeded gradient error.
You're done when
Your dense-layer backward matches centered differences to 1e-8 relative and a directional test to 1e-9 absolute, and you can move the error up and down the U-curve by changing .
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 3 more in the section
- MIT 18.S096 - Matrix Calculus for MLMIT OpenCourseWare · primary
Use lectures 1-5, the Hessian portion of lecture 7 and computational-graph portion of lecture 8; do the supplied problems and notebooks.
- Hands-On ML - Autodiff notebookAurelien Geron · required
Work through numerical differentiation and both AD modes, then rebuild the essential reverse-mode engine independently.
- Mathematics for Machine Learning - Ch. 5Deisenroth, Faisal & Ong · reference
Use Chapter 5 as the compact derivative, Jacobian, chain-rule and backpropagation reference.
Also in this section
- PyTorch Autograd mechanicsPyTorch documentation · required
Consult after the handwritten engine for accumulation, graph behavior, disabled tracking and vector-Jacobian products.
- MIT 18.02SC - Multivariable Calculus Unit 2MIT OpenCourseWare · optional
Use sessions 24-38 only if partial derivatives, gradients, Hessians or the multivariable chain rule are weak.
- CS231n - Linear ClassificationStanford University · support
Read the Softmax classifier section for the cross-entropy loss formula with both the information-theory and MLE views, and Practical issues: Numeric stability for the max-subtraction trick. Derive the softmax gradient by hand; do not implement the course assignment here.