TExcelTAD
Home › Math for Machine Learning › Checking Gradients Numerically

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 f(x±h)=f(x)±hf′(x)+h22f′′(x)±h36f′′′(x)+⋯f(x \pm h) = f(x) \pm hf'(x) + \frac{h^2}{2}f''(x) \pm \frac{h^3}{6}f'''(x) + \cdots:

f(x+h)−f(x)h=f′(x)+h2f′′(x)+⋯forward difference, error O(h)f(x+h)−f(x−h)2h=f′(x)+h26f′′′(x)+⋯central difference, error O(h2)\begin{aligned} \frac{f(x + h) - f(x)}{h} &= f'(x) + \frac{h}{2}f''(x) + \cdots && \text{forward difference, error } O(h) \\ \frac{f(x + h) - f(x - h)}{2h} &= f'(x) + \frac{h^2}{6}f'''(x) + \cdots && \text{central difference, error } O(h^2) \end{aligned}

The central difference cancels the h2h^2 term and is far more accurate for the same hh. Always use it for gradient checks.

Choosing hh: truncation versus rounding

Smaller hh shrinks the Taylor (truncation) error but amplifies floating-point rounding: f(x+h)f(x + h) and f(x−h)f(x - h) 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 h≈10−5h \approx 10^{-5} to 10−610^{-6}.

python · try it yourself
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 h2h^2 until about h=10−5h = 10^{-5}, then rounding takes over and it grows again.

Relative error

Compare analytic gradient ga\mathbf{g}_a and numeric gradient gn\mathbf{g}_n with a scale-free measure:

rel=∥ga−gn∥max⁡(∥ga∥+∥gn∥,ϵ)\text{rel} = \frac{\lVert \mathbf{g}_a - \mathbf{g}_n \rVert}{\max(\lVert \mathbf{g}_a \rVert + \lVert \mathbf{g}_n \rVert, \epsilon)}

Rules of thumb in double precision: below 10−710^{-7} is correct; around 10−410^{-4} is suspicious; above 10−210^{-2} is a bug. Always check in float64, at random (not special) points, and through non-differentiable spots such as ReLU⁡\operatorname{ReLU} at 0 with care.

python · try it yourself
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.gradcheck and jax.test_util.check_grads implement exactly this test.
  • scipy.optimize.check_grad returns 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 hh divides the error by 4, which formula are you probably using?

Answer

The central difference.

Solution

Error ∝h2\propto h^2: halving hh gives a factor 22=42^2 = 4. The forward difference's error ∝h\propto h 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 (θi±h\theta_i \pm h) 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 ddxtanh⁡(x)=1+tanh⁡2(x)\frac{d}{dx}\tanh(x) = 1 + \tanh^2(x). Check it at x=0.5x = 0.5 with a central difference.

Answer

Wrong: the correct derivative is 1−tanh⁡2(x)1 - \tanh^2(x).

Solution
python · try it yourself
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 f(x+h)−f(x−h)2h\frac{f(x+h) - f(x-h)}{2h} shrinks like…

  1. hh
  2. h2h^2
  3. h3h^3
  4. it does not shrink

Why not use h=10−12h = 10^{-12} for a gradient check in double precision?

  1. It is too slow
  2. Rounding error dominates: f(x+h)f(x+h) and f(x−h)f(x-h) are almost equal and their difference loses precision
  3. The Taylor series diverges
  4. NumPy forbids it

A relative error of 10−910^{-9} between analytic and numeric gradients suggests…

  1. a bug
  2. the gradient is correct
  3. the step is too large
  4. the model is overfitting