Checking Gradients
A gradient check compares your analytic gradient with one estimated by nudging each input and watching the loss. If the two agree to many digits, the backward pass is right; if they don't, the check tells you which parameter is wrong. It is the standard test for any round that asks for backprop by hand, as Anthropic did when it asked candidates to write a small network's forward and backward passes (the question).
It takes about ten lines, runs in seconds on a tiny network, and is the difference between saying "I think the gradient is right" and showing it. This page covers how to write it, how to read the number it gives, and the cases where it lies.
Finite Differences
The derivative is the slope of the loss as one input moves, so you can estimate it by moving the input a little
both ways. The central difference (f(x + h) - f(x - h)) / (2h) has an error proportional to h^2; the
one-sided (f(x + h) - f(x)) / h has an error proportional to h, so the central one is far more accurate for
the same cost per side. For an array of parameters, nudge one entry at a time.
import numpy as np
def num_grad(f, x: np.ndarray, h: float = 1e-5) -> np.ndarray:
"""Central differences of the scalar f() with respect to x, which f reads in place."""
g = np.zeros_like(x)
for i in np.ndindex(x.shape):
old = x[i]
x[i] = old + h
f_plus = f()
x[i] = old - h
f_minus = f()
x[i] = old # always restore
g[i] = (f_plus - f_minus) / (2 * h)
return g
W = np.array([[1.0, -2.0], [0.5, 3.0]])
f = lambda: float((W ** 3).sum()) # d/dW = 3 W^2
assert np.allclose(num_grad(f, W), 3 * W ** 2, atol=1e-6)
Writing f as a function of no arguments that reads the parameter array in place is deliberate: it lets you
check any parameter of a model without restructuring the code. The cost is two forward passes per entry, so check
tiny models, or a random sample of entries for large ones.
Choosing the Step
The step h trades two errors against each other. A large h gives truncation error from the curvature; a tiny
h gives rounding error, because f(x + h) - f(x - h) subtracts two nearly equal numbers and loses digits.
Here are both estimates of the derivative of sin at 1, against the true cos(1):
for h in (1e-1, 1e-3, 1e-5, 1e-7, 1e-9):
fwd = (np.sin(1 + h) - np.sin(1)) / h
ctr = (np.sin(1 + h) - np.sin(1 - h)) / (2 * h)
print(f"h={h:.0e} forward {abs(fwd - np.cos(1)):.1e} central {abs(ctr - np.cos(1)):.1e}")
The central error falls from about 9e-4 at h = 1e-1 to about 1e-11 at h = 1e-5, then rises again to about
3e-9 at h = 1e-9 as rounding takes over; the forward difference is never better than about 4e-8. In float64,
use central differences with h around 1e-5 to 1e-6. In float32 the rounding floor is so high that a check is
barely useful, so always run gradient checks in float64.
Relative Error
An absolute difference means nothing without the size of the gradients, so compare with a relative error:
||a - b|| / (||a|| + ||b||). It is 0 when the two agree, 1 when one of them is zero and the other isn't, and it
doesn't care whether the gradients are around 1e-3 or 1e3. The norm form also avoids dividing by tiny
individual entries.
def rel_error(a: np.ndarray, b: np.ndarray) -> float:
return float(np.linalg.norm(a - b) / max(np.linalg.norm(a) + np.linalg.norm(b), 1e-12))
Rules of thumb for float64 with h = 1e-5: below 1e-7 the gradient is right; around 1e-5 to 1e-4 look
closer, since that can come from kinks; above 1e-3 there is almost certainly a bug. Report the number per
parameter, not one number for the whole model: a bug in one bias is invisible next to correct weight gradients
many times larger.
Checking a Hand-Written Backward Pass
Check each parameter of the model separately, with the loss as the scalar. Here is a one-hidden-layer ReLU network with a softmax cross-entropy loss, the network many backprop rounds ask for; An MLP with Backprop by Hand derives each line.
def loss_and_grads(p: dict, X: np.ndarray, y: np.ndarray, relu_mask: bool = True):
n = X.shape[0]
a = X @ p["W1"] + p["b1"] # (n, H)
h = np.maximum(a, 0) # (n, H)
z = h @ p["W2"] + p["b2"] # (n, C)
z = z - z.max(axis=1, keepdims=True)
P = np.exp(z) / np.exp(z).sum(axis=1, keepdims=True)
loss = -np.log(P[np.arange(n), y]).mean()
dz = P.copy()
dz[np.arange(n), y] -= 1
dz /= n # (n, C): softmax + CE combined
dh = dz @ p["W2"].T # (n, H)
da = dh * (a > 0) if relu_mask else dh # relu_mask=False plants a bug
grads = {"W2": h.T @ dz, "b2": dz.sum(0), "W1": X.T @ da, "b1": da.sum(0)}
return loss, grads
rng = np.random.default_rng(0)
X, y = rng.normal(size=(5, 4)), rng.integers(0, 3, size=5)
p = {"W1": rng.normal(size=(4, 6)), "b1": rng.normal(size=6),
"W2": rng.normal(size=(6, 3)), "b2": rng.normal(size=3)}
for bug in (False, True):
_, g = loss_and_grads(p, X, y, relu_mask=not bug)
errs = {k: rel_error(g[k], num_grad(lambda: loss_and_grads(p, X, y)[0], p[k])) for k in p}
print("bug" if bug else "ok ", {k: f"{e:.0e}" for k, e in errs.items()})
assert all(e < 1e-7 for e in errs.values()) != bug
With the correct backward pass, every parameter's relative error is below 1e-10. With the ReLU mask left out,
W2 and b2 still pass, while W1 and b1 jump to 0.4 and 0.5. That pattern is the point: the check names the
layer where the chain rule went wrong, here the first one below the output. Note that the numeric gradient always
comes from the true loss; only the analytic one has the bug.
When the Check Lies
A failing check doesn't always mean a bug, and a few situations produce false alarms or hide real errors. The
most common is a kink: ReLU, max and abs have no derivative at their corners, and if an input sits within h
of one, the two sides of the difference see different slopes.
x = np.array([1e-6]) # just right of ReLU's kink at 0
f = lambda: float(np.maximum(x, 0).sum())
print(num_grad(f, x)) # about 0.55, while the analytic slope is 1
The numeric estimate here is 0.55 against the true slope of 1, because the step of 1e-5 crosses the corner. The
other cases, each with its fix:
- Kinks. Symptom: a handful of large errors in an otherwise good check. Fix: use random inputs, which rarely
land within
hof a corner, or check withtanhin place of ReLU, then swap it back. - Randomness. Symptom: a check that fails by a different amount each run. Dropout or sampling draws new
random numbers on each forward pass. Fix: fix the seed inside
f, or turn dropout off for the check. - Low precision. Symptom: errors around
1e-3everywhere. Fix: float64, always. - A tiny loss. Symptom: relative errors look fine because everything is near zero. Fix: random, non-trivial weights, so gradients are of order 1.
gradcheck in PyTorch
In PyTorch you rarely need a numeric check for built-in layers, since autograd is already right, but you need
one for a custom torch.autograd.Function with a hand-written backward. torch.autograd.gradcheck does the
finite differences for you and compares every entry, and like any check it needs float64 inputs.
import torch
class Swish(torch.autograd.Function): # x * sigmoid(x), with a hand-written backward
@staticmethod
def forward(ctx, x: torch.Tensor) -> torch.Tensor:
s = torch.sigmoid(x)
ctx.save_for_backward(x, s)
return x * s
@staticmethod
def backward(ctx, g: torch.Tensor) -> torch.Tensor:
x, s = ctx.saved_tensors
return g * (s + x * s * (1 - s)) # product rule: s + x s (1 - s)
x = torch.randn(8, dtype=torch.float64, requires_grad=True)
assert torch.autograd.gradcheck(Swish.apply, (x,))
x32 = x.detach().float().requires_grad_()
print(torch.autograd.gradcheck(Swish.apply, (x32,), raise_exception=False)) # float32: fails
The float64 check passes; the same correct function in float32 fails gradcheck's default tolerances, which is
the low-precision false alarm from the list above. gradcheck is also useful for a whole module written from
primitives, as a test that your masking or masked_fill doesn't produce a NaN gradient; the
self-attention write-up uses it that way.
Key Takeaways
- Use central differences,
(f(x + h) - f(x - h)) / 2h, withharound1e-5, in float64. - Compare with the relative error
||a - b|| / (||a|| + ||b||): below1e-7is right, above1e-3is a bug. - Check each parameter separately; the first failing layer from the output is where the chain rule broke.
- Kinks, randomness and float32 cause false alarms: use random inputs, fix seeds, use float64.
- In PyTorch,
torch.autograd.gradcheckchecks custombackwardmethods; give it float64 inputs.