Gradient checking
梯度检查
Compare analytic derivatives with finite differences, select a meaningful perturbation scale, and distinguish an incorrect gradient from a nondifferentiable point.
gradient-checkingA 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 , the analytic gradient is . 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 , central finite differences give:
Expanding both function values around , the even-order terms cancel. With sufficient smoothness, the derivative error from truncating the expansion is . Subtraction and division amplify errors in the function values, often contributing a term proportional to machine precision divided by . Consequently, making 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:
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 , a cheaper check is:
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 parameters and forward evaluation cost , a full coordinate check takes evaluations, or work plus vector copying. The simple copying implementation adds work; in-place perturbations with careful restoration can avoid that overhead. Its working vectors use 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 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
- 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.
- Why not use only relative error when both gradients are almost zero? Answer: the denominator is tiny; absolute tolerance is needed.
- Can one directional check miss a wrong gradient? Answer: yes, when the gradient error is orthogonal to that direction.
- 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?
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
- Deep Learning — Chapter 4: Numerical Computation
Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016 - 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:
- Deep Learning — Chapter 4: Numerical Computation · §4.1–4.3: floating-point errors, conditioning and gradient-based calculations; central-difference remainder re-derived in article
- PyTorch Tutorial — Double Backward with Custom Functions · Saving the Inputs example and introduction: double precision for gradcheck; first versus second backward support
Related topics