Checking Gradients Numerically
A wrong gradient does not crash: training just behaves strangely, and you can lose days. The cure is cheap. Compare your analytic gradient with a finite-difference estimate on a few random inputs before trusting it. This lesson shows which difference formula to use, how to choose the step, and how to read the result.
Finite differences
From the Taylor expansion :
The central difference cancels the term and is far more accurate for the same . Always use it for gradient checks.
Choosing : truncation versus rounding
Smaller shrinks the Taylor (truncation) error but amplifies floating-point rounding: and agree in most digits, and their difference loses precision. With double precision (about 16 significant digits), the total error of the central difference is smallest near to .
import numpy as np
f, df = np.sin, np.cos
x = 1.0
print(" h forward err central err")
for h in (1e-1, 1e-3, 1e-5, 1e-7, 1e-9, 1e-11):
fwd = (f(x + h) - f(x)) / h
cen = (f(x + h) - f(x - h)) / (2 * h)
print(f"{h:.0e} {abs(fwd - df(x)):.2e} {abs(cen - df(x)):.2e}") h forward err central err
1e-01 4.29e-02 9.00e-04
1e-03 4.21e-04 9.01e-08
1e-05 4.21e-06 1.11e-11
1e-07 4.18e-08 1.94e-10
1e-09 5.25e-08 2.97e-09
1e-11 1.17e-06 1.17e-06
The central error falls like until about , then rounding takes over and it grows again.
Relative error
Compare analytic gradient and numeric gradient with a scale-free measure:
Rules of thumb in double precision: below is correct; around is suspicious; above is a bug. Always check in float64, at random (not special) points, and through non-differentiable spots such as at 0 with care.
import numpy as np
def logistic_loss(w, X, y):
z = X @ w
return np.mean(np.log1p(np.exp(-y * z)))
def grad_correct(w, X, y):
z = X @ w
return -(X.T @ (y / (1 + np.exp(y * z)))) / len(y)
def grad_buggy(w, X, y): # forgot the minus sign inside exp
z = X @ w
return -(X.T @ (y / (1 + np.exp(-y * z)))) / len(y)
def numeric(f, w, h=1e-6):
return np.array([(f(w + h * e) - f(w - h * e)) / (2 * h) for e in np.eye(len(w))])
def rel(a, b): return np.linalg.norm(a - b) / max(np.linalg.norm(a) + np.linalg.norm(b), 1e-12)
rng = np.random.default_rng(0)
X = rng.normal(size=(40, 4)); y = np.sign(rng.normal(size=40)); w = rng.normal(size=4)
gn = numeric(lambda v: logistic_loss(v, X, y), w)
print(f"correct gradient: rel error {rel(grad_correct(w, X, y), gn):.1e}")
print(f"buggy gradient: rel error {rel(grad_buggy(w, X, y), gn):.1e}")correct gradient: rel error 2.9e-10
buggy gradient: rel error 9.9e-01
Cost and practice
A full numerical gradient needs two function evaluations per parameter, so check a small model, or a random subset of coordinates of a big one. Turn off randomness (dropout, data shuffling) during the check, since the two evaluations must see the same function.
In software
torch.autograd.gradcheckandjax.test_util.check_gradsimplement exactly this test.scipy.optimize.check_gradreturns the norm of the difference for a function and its gradient.- Custom CUDA kernels and hand-derived backward passes in research code should always come with a gradient check.
Exercises
Exercise 1: Error orders
If halving divides the error by 4, which formula are you probably using?
Answer
The central difference.
Solution
Error : halving gives a factor . The forward difference's error would only halve.
Exercise 2: Count evaluations
How many loss evaluations does a central-difference check of a model with 2,000 parameters need?
Answer
4,000.
Solution
Two evaluations () per parameter. One backward pass gives all 2,000 analytic partial derivatives for the cost of a few evaluations, which is the whole point of backprop.
Exercise 3: Catch a bug (code)
A student claims . Check it at with a central difference.
Answer
Wrong: the correct derivative is .
Solution
import numpy as np
x, h = 0.5, 1e-6
num = (np.tanh(x + h) - np.tanh(x - h)) / (2 * h)
print(round(num, 8), round(1 + np.tanh(x)**2, 8), round(1 - np.tanh(x)**2, 8))0.78644773 1.21355227 0.78644773
Test yourself
The error of the central difference shrinks like…
- it does not shrink
Why not use for a gradient check in double precision?
- It is too slow
- Rounding error dominates: and are almost equal and their difference loses precision
- The Taylor series diverges
- NumPy forbids it
A relative error of between analytic and numeric gradients suggests…
- a bug
- the gradient is correct
- the step is too large
- the model is overfitting