AI Wiki中文/EN

Gradient checking

梯度检查

Compare analytic derivatives with finite differences, select a meaningful perturbation scale, and distinguish an incorrect gradient from a nondifferentiable point.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A loss decreasing once is a weak derivative test

Suppose a custom backward function accidentally returns twice the correct gradient. With a small learning rate, training may still lower the loss. Watching a loss curve does not necessarily expose the error. A derivative check asks a more direct question: does the claimed slope agree with the loss changes produced by controlled perturbations?

For f(x,y)=x2y+sin⁡yf(x,y)=x^2y+\sin y, the analytic gradient is (2xy,x2+cos⁡y)(2xy,x^2+\cos y). This small function has interacting inputs and a nonlinear term, making it more informative than checking a single linear operation. We can compare each coordinate and also test directional derivatives.

Approximation error competes with rounding error

For a coordinate unit vector eie_i, central finite differences give:

ginum(h)=f(θ+hei)−f(θ−hei)2h.g_i^{\mathrm{num}}(h)=\frac{f(\theta+he_i)-f(\theta-he_i)}{2h}.

Expanding both function values around θ\theta, the even-order terms cancel. With sufficient smoothness, the derivative error from truncating the expansion is O(h2)O(h^2). Subtraction and division amplify errors in the function values, often contributing a term proportional to machine precision divided by hh. Consequently, making hh arbitrarily small can make the estimate worse. Numerical conditioning and floating-point limitations matter even when the algebra is correct. Deep Learning, Sections 4.1–4.3

A practical componentwise comparison combines absolute and relative tolerances:

∣ginum−giclaimed∣≤atol+rtolmax⁡(∣ginum∣,∣giclaimed∣).|g_i^{\mathrm{num}}-g_i^{\mathrm{claimed}}|\le\mathrm{atol}+\mathrm{rtol}\max(|g_i^{\mathrm{num}}|,|g_i^{\mathrm{claimed}}|).

Absolute tolerance matters near zero, where a relative ratio can explode. Relative tolerance matters when derivative scales differ greatly. Try a range of perturbations and inspect the actual numbers; one fixed tolerance is not a proof for every function and dtype. Double precision is useful for numerical derivative checks, as illustrated by PyTorch’s custom-autograd tutorial. PyTorch tutorial

For a direction vv, a cheaper check is:

f(θ+hv)−f(θ−hv)2h≈∇f(θ)⊤v.\frac{f(\theta+hv)-f(\theta-hv)}{2h}\approx\nabla f(\theta)^\top v.

One direction needs two function evaluations regardless of the number of parameters. It can miss an error orthogonal to that direction. Several independently chosen directions improve coverage but do not certify every component. Coordinate checks provide more localization at higher cost.

Make the test reject a known wrong derivative

The complete program compares the two analytic components, checks a directional derivative, and deliberately corrupts one component to ensure the comparison fails. It uses deterministic float64-style Python floats and independent copies of perturbed inputs.

import math

def loss(theta):
    x,y = theta
    return x*x*y+math.sin(y)

def gradient(theta):
    x,y = theta
    return [2*x*y,x*x+math.cos(y)]

def central(function, theta, h=1e-5):
    if not math.isfinite(h) or h <= 0:
        raise ValueError("positive finite perturbation required")
    result = []
    for i in range(len(theta)):
        plus,minus = list(theta),list(theta)
        plus[i] += h
        minus[i] -= h
        result.append((function(plus)-function(minus))/(2*h))
    return result

def agrees(a,b,atol=1e-8,rtol=1e-6):
    return len(a)==len(b) and all(math.isfinite(x) and math.isfinite(y)
           and abs(x-y) <= atol+rtol*max(abs(x),abs(y)) for x,y in zip(a,b))

for theta in ([0.7,-0.4],[-1.2,0.3],[0,0]):
    numerical = central(loss,theta)
    analytic = gradient(theta)
    assert agrees(numerical,analytic)
    wrong = analytic.copy()
    wrong[1] += 0.1
    assert not agrees(numerical,wrong)
theta, direction, h = [0.7,-0.4],[0.6,0.8],1e-5
plus = [x+h*v for x,v in zip(theta,direction)]
minus = [x-h*v for x,v in zip(theta,direction)]
numeric = (loss(plus)-loss(minus))/(2*h)
assert agrees([numeric],[sum(g*v for g,v in zip(gradient(theta),direction))])
relu_difference = (max(0,h)-max(0,-h))/(2*h)
assert relu_difference == 0.5
assert not agrees([float('nan')],[0])

For dd parameters and forward evaluation cost CfC_f, a full coordinate check takes 2d2d evaluations, or O(dCf)O(dC_f) work plus vector copying. The simple copying implementation adds O(d2)O(d^2) work; in-place perturbations with careful restoration can avoid that overhead. Its working vectors use O(d)O(d) space. Gradient checking is a diagnostic for small cases, not an efficient replacement for backpropagation during training.

Keep both sides on the same function

At a ReLU kink, a central difference can disagree with a framework’s chosen derivative convention without proving a bug. For f(x)=max⁡(0,x)f(x)=\max(0,x) at zero, central differences return one half, while a common backward convention returns zero. Test smooth points or explicitly account for the convention and which branches perturbations cross.

Random dropout masks, changing batch statistics, mutable buffers, and nondeterministic operations can make the two evaluations represent different functions. Control randomness and state. Switching a whole model to evaluation mode may help some checks but also changes its computation; document which function is being tested.

Aliased storage can perturb more than one logical input at once. Detached paths can make both the claimed graph and a carelessly designed reference omit the same intended dependency. Checks must compare against the intended forward function, and passing a few inputs does not establish correctness everywhere. Higher-order derivatives need additional checks; a valid first backward pass does not guarantee a valid second one. PyTorch, double-backward discussion

Decide whether disagreement is informative

  1. Why can a gradient scaled by two still produce a falling loss? Answer: it changes the effective step size, and a small enough step can still descend.
  2. Why not use only relative error when both gradients are almost zero? Answer: the denominator is tiny; absolute tolerance is needed.
  3. Can one directional check miss a wrong gradient? Answer: yes, when the gradient error is orthogonal to that direction.
  4. Does a ReLU difference of 0.5 at zero prove its backward implementation is wrong? Answer: no. The point is nondifferentiable, and a derivative convention must be considered.

Use a small diagnostic before a large training run

Check shapes, scalar losses, shared-operand accumulation, masks, and several input scales before trusting a custom operation. Combine derivative checks with independent forward-result checks: an internally consistent backward pass can correctly differentiate the wrong forward formula. Record the inputs, dtype, tolerances, and expected failure cases so the check can be reproduced.

Make a prediction, then check

Is a smaller perturbation h always better for central differences?

Choose one answer

Learning objectives

  • Compare analytic gradients with central differences using absolute and relative tolerances.
  • Explain perturbation scales, nondifferentiable points, random state, and directional-check coverage.

Prerequisites & connections

Explore related knowledge →

References

  1. Deep Learning — Chapter 4: Numerical Computation
    Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016
  2. PyTorch Tutorial — Double Backward with Custom Functions
    PyTorch tutorial contributors · 2021

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check: cited-source comparison, re-derivation and recalculation, bilingual argument comparison, and executed Python assertions; no independent human peer review.

  • Re-derived even-order cancellation and the conditions for O(h²) central-difference error; 30 random inputs matched analytic gradients and all deliberately added 0.1 errors were rejected.
  • Executed directional checks, the ReLU-at-zero 0.5 difference, and NaN rejection; checked perturbation scales, tolerances, copying overhead, random state, and shared-storage limits.
  • Compared bilingual arguments, conditions, examples, and exercise answers; structural checks separately compare formulas, code, sections, and references. No independent human peer review.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.