7 routes42 sections324 units

Unit 1.5 · about 3 h

174 / 324

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.

  • 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

  1. The gradient-check protocol
    CS231n 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

  2. Where the formula comes from
    D2L - 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.

  3. Framework defaults and the overlap warning
    `torch.autograd.gradcheck` API and tolerances

    Signature defaults eps 1e-6, atol 1e-5, rtol 1e-3; the note that checked tensors with overlapping memory, for example expand outputs, 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 in float32 against about 6e-11 in float64. 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

Closed-book, implement 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

  1. One-sided differences on \(\exp\) at 1 with \(h = 10^{-5}\) err by about 1.4e-5. What does centered achieve, and why?

  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?

  3. Both analytic and numerical gradients are exactly 0. Pass or fail?

  4. A correct gradient shows relative error near 1e-2 in float32. What do you change?

  5. Why does torch gradcheck warn about expand outputs as inputs?

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.

Mark passed, then open 1.6 Only mark this when you can do it without notes.

Leads to

Comes after

Resources for this unit

  • D2L - tensors, autograd, MLP and backpropagation
    D2L authorsrequiredimplementation
    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
    Stanford CS231nreferencereference
    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
    PyTorchreferencereference
    Read the gradcheck signature defaults (eps 1e-6, atol 1e-5, rtol 1e-3) and the note that inputs with overlapping memory, such as expand outputs, will likely fail the check.

Also in this section

  • Understanding Deep Learning - Chapters 3 to 7
    Simon J. D. Princeprimarytheory
    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
    TensorTonicrequiredpractice
    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
    Deep-MLoptionalpractice
    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
    Stanford CS231nreferencereference
    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
    PyTorchreferencereference
    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`
    PyTorchreferencereference
    Read the ignore_index and reduction parameters: ignored targets contribute no gradient, and mean reduction averages over the non-ignored targets only.
  • PyTorch Tensor Views
    PyTorchreferencereference
    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: reshape may copy, contiguous copies only when needed, basic indexing returns views while advanced indexing copies.
  • `torch.Tensor.stride` - stride and storage offset
    PyTorchreferencereference
    Read the stride definition: strides are per-dimension element steps, and with storage_offset they locate every element. Combine with the Tensor Views page for transposed and expanded layouts.
  • PyTorch Autograd mechanics - in-place operations
    PyTorchreferencereference
    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
    PyTorchreferencereference
    Read the parameters and buffers documentation: modules collect parameters recursively for the optimizer, while register_buffer holds persistent non-parameter tensors saved alongside them.

Quick find

Search Michi

Type to search every route, section, unit, topic and resource.

Enter opens the first result Esc closes

Reference

Keyboard shortcuts

n
Continue to the first unit not passed
j / k
Next / previous unit
1 2 3
Toggle learned, practised, passed
/
Open search
?
Show this help
Esc
Close open panels