Gradient Checking for Neural Networks
A backward-pass error can leave array shapes intact and even allow the loss to decrease. Gradient checking compares the implemented derivative with a numerical estimate at selected inputs and parameters. Agreement is useful evidence about that computation, not a proof for every input, and it does not show that the chosen loss or data pipeline matches the task.
Central differences
For a sufficiently smooth scalar objective \(J\), forward differences have truncation error \(O(h)\) and central differences have truncation error \(O(h^2)\). These describe exact-arithmetic approximations as the step \(h\) shrinks. Floating-point subtraction introduces another error, often growing roughly like machine precision divided by \(h\). Therefore a smaller step need not improve accuracy, and neither formula promises a fixed number of correct digits:
\[\frac{\partial J}{\partial\theta_i}\approx\frac{J(\theta+\epsilon e_i)-J(\theta-\epsilon e_i)}{2\epsilon}\]
Here \(\theta\) is the flattened parameter vector and \(e_i\) changes only coordinate \(i\). We use central differences with \(h=\epsilon\). For \(J(\theta)=\theta^2\) at \(\theta=3\), a step of 0.01 gives \((3.01^2-2.99^2)/0.02=6\), matching \(2\theta\). Central differences are a useful default for these small smooth examples; SciPyโs check_grad, for example, uses forward differences, so compare conventions rather than treating one formula as mandatory.
The chain-rule machinery behind every gradient here is derived in Derivatives and Computation Graphs for Neural Network Learning.
Comparing with relative error
Use absolute and relative discrepancies together. A difference of \(10^{-4}\) is large relative to gradients of size \(10^{-5}\), but small relative to gradients of size \(10^3\). A full-vector summary is:
\[\text{rel}=\frac{\lVert g_{\text{approx}}-g_{\text{backprop}}\rVert_2}{\lVert g_{\text{approx}}\rVert_2+\lVert g_{\text{backprop}}\rVert_2}\]
If both gradient vectors are exactly zero, the denominator is zero; the implementation reports zero discrepancy in that case, but the check may be uninformative. Near-zero components need an absolute tolerance. A small aggregate relative error can hide errors in a small parameter block, so inspect components as well.
There is no universal โcorrect below \(10^{-7}\)โ cutoff. Sweep several perturbation sizes, such as \(10^{-4},10^{-5},10^{-6}\) for float64 parameters near unit scale, and look for a stable range of agreement. Large discrepancies can arise from a bug, rounding, nondeterminism, or crossing a nonsmooth point. The practical tolerance depends on the loss scale, precision, and model.
A complete implementation
import numpy as np
def flatten(params, keys):
return np.concatenate([params[k].ravel() for k in keys])
def unflatten(vec, params, keys):
out, i = {}, 0
for k in keys:
size = params[k].size
out[k] = vec[i:i+size].reshape(params[k].shape).copy()
i += size
if i != vec.size:
raise ValueError("Parameter vector has the wrong length")
return out
def gradient_check(cost_fn, params, grads, epsilon=1e-5):
if not params or not np.isfinite(epsilon) or epsilon <= 0:
raise ValueError("Provide parameters and a positive finite step")
keys = sorted(params)
for k in keys:
if params[k].dtype != np.float64:
raise ValueError("Use float64 parameters for this checker")
if grads["d"+k].shape != params[k].shape:
raise ValueError(f"Gradient shape mismatch for {k}")
theta = flatten(params, keys)
g_backprop = flatten(grads, ["d"+k for k in keys])
if not np.isfinite(theta).all() or not np.isfinite(g_backprop).all():
raise ValueError("Nonfinite parameters or analytic gradients")
g_approx = np.zeros_like(theta)
for i in range(theta.size):
plus, minus = theta.copy(), theta.copy()
plus[i] += epsilon
minus[i] -= epsilon
if plus[i] == theta[i] or minus[i] == theta[i]:
raise ValueError("Perturbation rounded away; rescale or change step")
values = [np.asarray(cost_fn(unflatten(v, params, keys)))
for v in (plus, minus)]
if any(v.ndim != 0 or not np.isfinite(v) for v in values):
raise ValueError("cost_fn must return a finite scalar")
g_approx[i] = (float(values[0])-float(values[1]))/(2*epsilon)
if not np.isfinite(g_approx).all():
raise ValueError("Nonfinite numerical gradient")
num = np.linalg.norm(g_approx-g_backprop)
den = np.linalg.norm(g_approx)+np.linalg.norm(g_backprop)
return (0.0 if den == 0 else num/den), g_approx, g_backprop
W1 pairs with dW1. Both vectors use the same explicit key order; sorting is one way to obtain that order, not a mathematical requirement. Run all blocks below in order. The checker expects real float64 arrays, matching gradient shapes, and a deterministic scalar cost. Casting parameters is insufficient if cost_fn internally casts back to float32 or changes state.
This example has two input features, three tanh hidden units, one linear output, and three examples stored in columns. Its 13 parameters minimize mean squared error. The division by the number of examples appears once, in dout. Smooth tanh avoids ReLU kink crossings while testing the checker itself.
X = np.array([[0.2, -0.4, 0.7], [1.0, 0.3, -0.2]])
Y = np.array([[0.5, -0.1, 0.8]])
rng = np.random.default_rng(4)
params = {"W1": rng.normal(0, 0.3, (3, 2)),
"b1": np.full((3, 1), 0.1),
"W2": rng.normal(0, 0.3, (1, 3)),
"b2": np.array([[0.2]])}
def model_cost(p):
hidden = np.tanh(p["W1"] @ X + p["b1"])
prediction = p["W2"] @ hidden + p["b2"]
return np.mean((prediction-Y)**2)
def model_grads(p):
hidden = np.tanh(p["W1"] @ X + p["b1"])
prediction = p["W2"] @ hidden + p["b2"]
dout = 2*(prediction-Y)/X.shape[1]
dhidden = (p["W2"].T @ dout)*(1-hidden**2)
return {"dW2": dout @ hidden.T,
"db2": dout.sum(axis=1, keepdims=True),
"dW1": dhidden @ X.T,
"db1": dhidden.sum(axis=1, keepdims=True)}
grads = model_grads(params)
for h in (1e-4, 1e-5, 1e-6):
rel, numerical, analytic = gradient_check(model_cost, params, grads, h)
print(f"h={h:.0e} rel={rel:.2e} max_abs={np.max(abs(numerical-analytic)):.2e}")
# h=1e-04 rel=7.34e-10 max_abs=6.42e-10
# h=1e-05 rel=6.99e-12 max_abs=5.49e-12
# h=1e-06 rel=3.04e-11 max_abs=1.94e-11
The checker makes two forward evaluations per parameter, so each step-size trial uses 26 forward passes. It compares the actual backward formulas above with the cost at the same parameter values.
Localizing the failure
To localize a discrepancy, map vector entries back to their parameter names and coordinates. Rank absolute discrepancies and report component-wise relative errors beside them. Large components can dominate absolute rankings, while near-zero components can dominate relative rankings; inspect both.
def worst_offenders(g_approx, g_backprop, params, k=5):
labels = [(name, index) for name in sorted(params)
for index in np.ndindex(params[name].shape)]
absolute = np.abs(g_approx-g_backprop)
denominator = np.abs(g_approx)+np.abs(g_backprop)
relative = np.divide(absolute, denominator, out=np.zeros_like(absolute),
where=denominator > 0)
indices = np.argsort(absolute)[::-1][:k]
return [(labels[i], float(absolute[i]), float(relative[i])) for i in indices]
bad_grads = {k: v.copy() for k, v in grads.items()}
bad_grads["dW1"] *= 2
rel, numerical, analytic = gradient_check(model_cost, params, bad_grads)
for (name, index), absolute, relative in worst_offenders(numerical, analytic, params, 3):
print(name, index, "relative", round(relative, 6))
# W1 (2, 0) relative 0.333333
# W1 (0, 0) relative 0.333333
# W1 (2, 1) relative 0.333333
A discrepancy concentrated in one block narrows the search to its derivative, forward computation, cache, or parameter mapping; it does not uniquely identify that layerโs backward function. A common multiplicative discrepancy suggests a scaling mismatch, such as sum versus mean, loss weights, or regularization coefficients. Compare the actual objectives and intermediate quantities before assigning a cause.
Rules for running the check
- Start with float64 for both forward and backward calculations and sweep the step size. Float32 can work with suitable tolerances and steps, but small perturbations are much more vulnerable to rounding.
- Disable dropout when checking the deterministic network, or freeze and reuse its mask in every forward and backward evaluation to test the dropout path itself. Also freeze data, augmentation, and mutable state. For training-mode BatchNorm, use the same batch and recompute its statistics consistently without accumulating running-state changes.
- Include the regularization term in
cost_fnif the backward pass includes it, and exclude it if not. - Use a tiny model with a few examples and units. A full coordinate check takes two forward passes per parameter. Checking sampled coordinates or a random directional derivative can reduce cost, but a subset can miss errors elsewhere.
- Check several nonspecial parameter settings, including initialization and a saved state after a few updates. Recompute analytic gradients for exactly the parameters under test.
- For ReLU, compare activation masks at the plus and minus parameter perturbations. A parameter step does not necessarily change a pre-activation by the same amount, so checking whether its distance from zero is below epsilon is insufficient. If masks change, reduce the step or test another point and report the excluded kink-crossing case.
A debugging order that saves time
Data inspection and shape checks often cost less than a full numerical check. Start there, then choose the next experiment based on what fails. Passing one check narrows the search but does not rule out other errors.
- Inspect inputs and labels first. View a batch after preprocessing and augmentation. Check target encoding, shapes, finite values, feature scales, and whether the split matches the intended evaluation.
- Inspect the initial predictions and loss. Uniform categorical probabilities give cross-entropy \(\log C\) for every class label, regardless of class balance. Random initialization need not produce uniform predictions. A discrepancy from this baseline calls for inspecting scores and the loss definition, not automatically declaring a bug.
- Check a miniature backward pass. Use the same scalar cost, data, parameters, regularization, and deterministic state. Inspect both absolute and relative errors across step sizes.
- Try fitting a tiny fixed batch. Reduce regularization and disable augmentation. Verify that the model can represent the chosen labels: conflicting labels on identical inputs, limited capacity, or unsuitable optimization can prevent a near-zero loss without an implementation bug. Success tests fitting ability on that batch, not generalization.
- Explore the learning rate and actual updates. A logarithmic sweep is useful, but no fixed range covers every parameterization or data scale. Confirm that the intended parameters are in the optimizer and change after its step.
- Inspect layer statistics over time. Track gradient and update norms and, where the parameter norm is nonzero, \(\|\Delta\theta\|/\|\theta\|\). There is no universal target ratio of \(10^{-3}\). For zero-initialized parameters, report absolute update size instead.
Seeding, configuration, and checkpointing for runs like this are covered in Reproducible Training Pipelines: Seeds, Configs, and Checkpoints.
What to log on every run
Log enough context to compare runs: the loss definition and reduction, training and validation metrics, learning-rate schedule, gradient norms, actual update sizes, and activation statistics for selected layers. For ReLU, report the fraction of zero activations or units inactive across the observed batches; one zero output does not show that a unit is permanently dead.
A flat loss with nonzero gradients could reflect a small learning rate, skipped optimizer steps, frozen parameters, or misleading logging. Small gradients can arise from saturation, a stationary point, or an incorrect graph. A spike calls for tracing the first changed or nonfinite quantity. Use the logs to select an experiment rather than to infer a unique cause.
How to decide which improvement to attempt next is the subject of A Systematic Strategy for Improving Machine Learning Models.
References
Discover more from Insightful Data Lab
Subscribe to get the latest posts sent to your email.
