Unit 5 of 7 · about 3 hours · implement, measure
Gradient checks with finite differences
An analytic gradient is a claim, and this unit is the assay. Every engine and loss in this section ships only after finite differences confirm it, within a tolerance you can defend.
You'll be able to
- Implement a centered-difference gradient checker with relative error in
float64, and state its pass thresholds. - Diagnose check failures from step size, precision, kinks, regularization, nondeterminism and overlapping memory.
- Decide where a check applies: a few parameters, a few datapoints, at a characteristic point, with noise turned off.
Covers
Read
In this order, only the parts listed
0 of 3 done
- The gradient-check protocolCS231n Neural Networks 3 - Gradient checks
Gradient Checks: the centered formula with error, relative error with the 1e-2 / 1e-4 / 1e-7 bands, double precision, near 1e-5, kinks at ReLU, few datapoints, burn-in point, regularization and dropout discipline, and checking a few dimensions per parameter
- Where the formula comes fromD2L - tensors, autograd, MLP and backpropagation
The limit definition of the derivative and the linear approximation : finite differences evaluate the quotient at small nonzero instead of taking the limit
Read for the definition only. The centered formula, error orders and protocol all come from the CS231n note above.
- Framework defaults and the overlap warning`torch.autograd.gradcheck` API and tolerances
Signature defaults
eps1e-6,atol1e-5,rtol1e-3; the note that checked tensors with overlapping memory, for exampleexpandoutputs, will likely fail
Focus on
- Use the centered form . On at 1 with it errs by about 6e-11 (second order), while one-sided errs by about 1.4e-5 (first order).
- Compare with relative error and pass both-zero explicitly. CS231n bands: above 1e-2 probably wrong, 1e-4 to 1e-2 uncomfortable, below 1e-4 fine with kinks, 1e-7 or less happy.
- Run in
float64: centered differences on at 1 err by about 1e-2 infloat32against about 6e-11 infloat64. Smaller is not always better; roundoff grows as truncation shrinks. - ReLU at exactly 0 gives centered 0.5 against analytic 0, a relative error of 1: the signature of a crossed kink, not a broken derivative. Check few datapoints, past burn-in, with regularization off and noise seeded or disabled.
Common mistakes · 3
- Using absolute error on tiny gradients. A 1e-4 gap on 1e-5 gradients is a huge failure; relative error exists for exactly this case.
- Checking with regularization on or dropout active. The simple regularization gradient then dominates or noise swamps the comparison, masking a wrong data-loss gradient.
- Perturbing one element of expanded or otherwise overlapping memory. Every aliased index moves at once, so the numerical gradient is meaningless and the check fails on correct code.
Try it yourself
Closed-book, before checking anything
gradcheck(f, x) with centered differences in float64, and relative error. Show matching to below 1e-7, and ReLU at 0 giving 0.5 against analytic 0.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.One-sided differences on at 1 with err by about 1.4e-5. What does centered achieve, and why?Answer
About 6e-11. Taylor expansion cancels the first-order term, leaving error instead of .
2.Analytic gradient is 0 and numerical is 0.5 at a ReLU evaluated at 0. What is the relative error, and what does it mean?Answer
. The perturbations crossed the kink, so the centered quotient averages both sides; it indicts the check point, not the implementation.
3.Both analytic and numerical gradients are exactly 0. Pass or fail?Answer
Pass, by an explicit both-zero rule. The ratio form would divide zero by zero.
4.A correct gradient shows relative error near 1e-2 in
float32. What do you change?AnswerRerun the check in
float64. Single-precision roundoff alone can fail a correct gradient; the same check drops to about 6e-11 infloat64.5.Why does torch
gradcheckwarn aboutexpandoutputs as inputs?AnswerExpanded indices share memory, so perturbing one index changes all its aliases at once. Point perturbation assumes independent coordinates.
Practice
- TensorTonic: Check a Product-Chain Gradient (autograd-l01-gradient-check-product-chain)
Derivatives and Gradient Checks section: Check a Product-Chain Gradient, after Estimate a Scalar Derivative and Measure Scalar Expression Partials
Write your own centered checker first with the bands above, then confirm it agrees with the platform tests.
- TensorTonic: Gradient-Check an Autodiff Graph (autograd-l05-autodiff-gradient-check)
Automatic Reverse-Mode Autodiff section: Gradient-Check an Autodiff Graph
Check a few dimensions per parameter in float64, past a short burn-in, with any noise disabled.
You're done when
Your checker reproduces the exp and ReLU-at-0 numbers from memory, and every earlier engine and loss in this section passes it in float64 with a defended threshold.
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 10 more in the section
- D2L - tensors, autograd, MLP and backpropagationD2L authors · required
Use chapter_preliminaries ndarray and autograd, then MLP, backpropagation, and numerical stability and initialization. Recreate scalar operations, affine maps, activation, reduction, stable cross-entropy, topological backward and unbroadcast in a blank file.
- CS231n Neural Networks 3 - Gradient checksStanford CS231n · reference
Read the Gradient Checks section only: centered formula with error, relative error with thresholds, double precision, step size near 1e-5, kinks, few datapoints, burn-in, regularization and dropout discipline, and checking a few dimensions per parameter.
- `torch.autograd.gradcheck` API and tolerancesPyTorch · reference
Read the
gradchecksignature defaults (eps1e-6,atol1e-5,rtol1e-3) and the note that inputs with overlapping memory, such asexpandoutputs, will likely fail the check.
Also in this section
- Understanding Deep Learning - Chapters 3 to 7Simon J. D. Prince · primary
Read Chapters 3-7, emphasizing Chapter 5 for likelihood-derived losses and Chapter 7 for backpropagation and initialization. Use notebooks 3.1, 4.1, 5.1, 6.1 and 7.1 only as equation and plot companions.
- TensorTonic - Build Micrograd from ScratchTensorTonic · required
Use the 25-problem Micrograd study plan in order for derivatives, gradient checks, value graphs, reverse mode, accumulation, operators, modules, losses and training. Preserve local tests as the evidence instead of a platform score.
- Deep-ML candidate - autograd and loss problemsDeep-ML · optional
After the five-sample platform check passes, use at most one of 26 Basic Autograd Operations, 997 Manual Cross-Entropy Backprop or 1227 Stable Softmax as a changed-prompt drill.
- CS231n Linear Classification - Softmax classifier and numeric stabilityStanford CS231n · reference
Read the Softmax classifier section for the cross-entropy form , then the Practical issues: Numeric stability part for the max-subtraction code
f -= np.max(f). - PyTorch Broadcasting semanticsPyTorch · reference
Read General semantics for the trailing-dimension rules, prepend-1 alignment and max-size result, with the
(5, 1, 4, 1)plus(3, 1, 1)examples; read In-place semantics for why an in-place tensor may not change shape. - `torch.nn.functional.cross_entropy` - `reduction` and `ignore_index`PyTorch · reference
Read the
ignore_indexandreductionparameters: ignored targets contribute no gradient, and mean reduction averages over the non-ignored targets only. - PyTorch Tensor ViewsPyTorch · reference
Read the view and storage sharing example (
data_ptr, mutating the view changes the base), the transpose non-contiguous example, the full view-ops list, and the special notes:reshapemay copy,contiguouscopies only when needed, basic indexing returns views while advanced indexing copies. - `torch.Tensor.stride` - stride and storage offsetPyTorch · reference
Read the stride definition: strides are per-dimension element steps, and with
storage_offsetthey locate every element. Combine with the Tensor Views page for transposed and expanded layouts. - PyTorch Autograd mechanics - in-place operationsPyTorch · reference
Read In-place operations with autograd (why in-place rewrites the graph and is discouraged) and In-place correctness checks (the version counter and the error on accessing a modified saved tensor).
- `torch.nn.Module` - parameters, buffers and statePyTorch · reference
Read the parameters and buffers documentation: modules collect parameters recursively for the optimizer, while
register_bufferholds persistent non-parameter tensors saved alongside them.