📝 Gradient Checking
Description
< What is it? >
Gradient checking is a debugging technique for verifying a hand-written backpropagation implementation. It compares the gradient from backpropagation with a numerical approximation computed from repeated forward passes.
For parameter vector , approximate the th gradient with the central-difference formula:
Here, changes only parameter , is a small number, and is the loss. Compare the approximation with the backpropagation gradient using relative difference:
Key points
< How to use it >
- Compute gradients with backpropagation.
- Flatten the model parameters and gradients into vectors.
- Perturb one parameter at a time by and , and run the forward pass for each.
- Compute and compare it with the backpropagation gradient.
A very small relative difference gives evidence that the implementation is correct. For a small float64 test,
approximately or lower is often reassuring, but the appropriate threshold depends on the loss scale,
parameter scale, and .
< When to use it >
- Use it while implementing or changing backpropagation, custom layers, or custom losses.
- Use a small model and a small batch: checking every parameter needs two extra forward passes per parameter, so it is too slow for ordinary training.
- Turn it off after debugging. Training should use backpropagation, not numerical gradients.
< Dropout and non-smooth operations >
Gradient checking assumes that and evaluate the same deterministic function.
- Disable dropout while checking, or otherwise ensure the same mask is used for both evaluations.
- Be careful near ReLU's zero boundary and other non-smooth points, where a numerical derivative can disagree even when backpropagation is correct.
Related ideas
- Backpropagation calculates the efficient analytical gradient used in training.
- Gradient Descent uses those gradients to update parameters.
- Vector norms explains the norm used in the relative-difference check.
Implementation
< Notebook >
- gradient checking (github)
Reference
- Introduction To Adam Optimizer (geeksforgeeks)
- Explaining Adam & Momentum for Gradient Descent Optimization (Paige Caskey)