Unit 1.5 · about 3 h
174 / 324Gradient 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.
- implement
- measure
You can now
- 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
- Finite-difference gradient checks and step-size limits
Study, in this order
3 steps
- The gradient-check protocolCS231n Neural Networks 3 - Gradient checks
Gradient Checks: the centered formula with \(O(h^2)\) error, relative error with the 1e-2 / 1e-4 / 1e-7 bands, double precision, \(h\) 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 \(f(x + \epsilon) \approx f(x) + \epsilon f'(x)\): finite differences evaluate the quotient at small nonzero \(\epsilon\) instead of taking the limit
Depth · 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 \((f(x+h) - f(x-h)) / 2h\). On \(\exp\) at 1 with \(h = 10^{-5}\) it errs by about 6e-11 (second order), while one-sided errs by about 1.4e-5 (first order).
- Compare with relative error \(|a - n| / \max(|a|, |n|)\) 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 \(\exp\) at 1 err by about 1e-2 infloat32against about 6e-11 infloat64. Smaller \(h\) 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.
Reproduce closed-book
gradcheck(f, x) with centered differences in float64, \(h = 10^{-5}\) and relative error. Show \(\exp\) matching to below 1e-7, and ReLU at 0 giving 0.5 against analytic 0.Traps
- 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.
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.
Self-test
-
One-sided differences on \(\exp\) at 1 with \(h = 10^{-5}\) err by about 1.4e-5. What does centered achieve, and why?
About 6e-11. Taylor expansion cancels the first-order term, leaving \(O(h^2)\) error instead of \(O(h)\). -
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?
\(|0 - 0.5| / \max(0, 0.5) = 1\). The perturbations crossed the kink, so the centered quotient averages both sides; it indicts the check point, not the implementation. -
Both analytic and numerical gradients are exactly 0. Pass or fail?
Pass, by an explicit both-zero rule. The ratio form would divide zero by zero. -
A correct gradient shows relative error near 1e-2 in
float32. What do you change?Rerun the check infloat64. Single-precision roundoff alone can fail a correct gradient; the same \(\exp\) check drops to about 6e-11 infloat64. -
Why does torch
gradcheckwarn aboutexpandoutputs as inputs?Expanded indices share memory, so perturbing one index changes all its aliases at once. Point perturbation assumes independent coordinates.
Completion criterion
Stop 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.
Leads to
- 2.4 Backward, `zero_grad`, `gradcheck` and evaluation modes Use the framework gradcheck with the same discipline.
- 3.7 Objective checks, tiny-set overfit and shuffled-label controls Extend checks to tiny-set overfit and shuffled-label controls.
Comes after
- 2.6 Backpropagation through dense layers and gradient checksThat unit standardizes centered differences in
float64with \(h = 10^{-5}\) and relative error; this unit's directional test is its matrix-valued companion. - 1.2 Stable softmax, cross-entropy and loss reductionsCheck the fused loss gradient against finite differences.
- 1.3 Computation graphs and reverse accumulationVerify the engine against finite differences.
- 1.4 Branches, broadcasting and saved values in backwardCheck the branched engine against finite differences.
- 2.4 Backward, `zero_grad`, `gradcheck` and evaluation modesRebuild finite-difference checks in your own engine.
Resources for this unit
- D2L - tensors, autograd, MLP and backpropagation 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 checks Read the Gradient Checks section only: centered formula with \(O(h^2)\) error, relative error with thresholds, double precision, step size \(h\) near 1e-5, kinks, few datapoints, burn-in, regularization and dropout discipline, and checking a few dimensions per parameter.
- `torch.autograd.gradcheck` API and tolerances 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 7 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 Scratch 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 problems 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 stability Read the Softmax classifier section for the cross-entropy form \(L_i = -f_{y_i} + \log \sum_j e^{f_j}\), then the Practical issues: Numeric stability part for the max-subtraction code
f -= np.max(f). - PyTorch Broadcasting semantics 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` Read the
ignore_indexandreductionparameters: ignored targets contribute no gradient, and mean reduction averages over the non-ignored targets only. - PyTorch Tensor Views 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 offset 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 operations 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 state Read the parameters and buffers documentation: modules collect parameters recursively for the optimizer, while
register_bufferholds persistent non-parameter tensors saved alongside them.