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

Backpropagation through dense layers and nonlinearitiesFinite-difference gradient checking and its failure modes
1

Read

In this order, only the parts listed

0 of 4 done

  1. 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)

  2. Numeric differentiation and the reverse engineHands-On ML - Autodiff notebook

    Cells Numeric differentiation (gradients() takes one-sided differences with eps = 1e-4 and calls; nesting it gives a Hessian whose exact 0 entry prints as -1.4e-6) and Reverse mode autodiff (hand engine with backpropagate, the artifact to test against differences)

  3. 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

  4. 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)

2

Focus on

  • Centered differences carry error until rounding at about takes over; in float64 sits 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 tanh layer 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 the tanh layer, float64 centered differences bottom out near 1e-10, not 1e-16.
3

Try it yourself

Closed-book, before checking anything

Closed-book, backpropagate with (), (), (), () and direction () drawn in that order with 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.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Write the backward pass for , , , with shapes.Answer

    , shape . (), , . The outer product, not an inner product, gives .

  2. 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. 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, dtype and norm.

  4. 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.

5

Practice

  • Deep-ML 313: Numerical Gradient Checking

    Implement numerical_gradient_check(f, x, analytical_grad, epsilon) with centered differences; tests check quadratics against rel_err < 1e-5

    The signature defaults epsilon to 1e-7. Sweep , explain why 1e-5 is safer in float64, 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.