Course outline

PyTorch / Storage, restoration, and transformed execution / Lesson 21

Gradient Checking Custom Computations

Compare analytical and numerical gradients on small controlled inputs before relying on a custom computation.

About 3 min readContent reviewed
On this page

Lesson goals

  • Explain finite-difference gradient checking and its limits.
  • Run gradcheck on small double-precision inputs.
  • Investigate failures caused by nondifferentiability or state.

Understand what is compared

A gradient check compares derivatives produced by automatic differentiation with numerical approximations obtained by perturbing inputs. Agreement within tolerance provides evidence for a particular function and test input; it does not prove correctness for all shapes, values, or devices. Begin with a deterministic, small example that avoids nondifferentiable boundaries.

The step size and tolerance affect the comparison. Very small perturbations can amplify floating-point error, while large ones may poorly approximate a local derivative. Follow the installed tool’s documentation and choose settings appropriate to the function and numerical precision.

Check one input

In a local lab with a compatible PyTorch installation, this example checks a smooth function using double-precision input with gradients enabled. The code requires an external library and is illustrative, so the public reader does not execute it. A passing result applies only to this fixture and configuration.

python Check a smooth function
import torch
from torch.autograd import gradcheck

def function(x):
    return x.sin() * x

x = torch.tensor([0.5, 1.0], dtype=torch.double, requires_grad=True)
print(gradcheck(function, (x,)))

The checker perturbs the input and compares numerical derivatives with those produced by autograd.

Check multiple inputs

A custom operation may depend on more than one differentiable input. Pass each input explicitly and use small values whose expected behavior is understandable. The second example checks a scalar product sum. Test realistic edge cases separately, including shape variations and any input that should not receive a gradient.

python Check two differentiable inputs
import torch
from torch.autograd import gradcheck

def function(x, y):
    return (x * y).sum()

x = torch.tensor([1.0, 2.0], dtype=torch.double, requires_grad=True)
y = torch.tensor([3.0, 4.0], dtype=torch.double, requires_grad=True)
print(gradcheck(function, (x, y)))

Both x and y require gradients, so the checker examines derivatives with respect to each input.

Diagnose a failure

A failure can indicate an incorrect backward implementation, an input near a nondifferentiable point, unsuitable precision or tolerance, overlapping storage, randomness, or mutable state. Reduce the function, fix the seed where appropriate, and inspect one input component. Do not simply loosen tolerance until the test passes without explaining the discrepancy.

Build a useful test set

Check representative shapes and values, boundary cases away from undefined derivatives, and supported dtypes or devices as appropriate. Compare ordinary forward outputs with an independent reference and add task-level tests. Record the environment and known limitations; a numerical check complements code review and integration tests rather than replacing them.

Common errors and fixes

A check fails near a sharp boundary.

Why it happens
The numerical perturbation crosses a nondifferentiable point.
How to fix it
Test a smooth region and separately specify boundary behavior.
Prevent it next time
Choose fixtures with known differentiability.

A check passes only after a very loose tolerance.

Why it happens
The discrepancy was hidden instead of explained.
How to fix it
Inspect numerical precision, step size, and the backward computation.
Prevent it next time
Set justified tolerances before accepting results.

Results vary between repeated checks.

Why it happens
Randomness or mutable state changed during function evaluation.
How to fix it
Isolate the state and make the test deterministic where possible.
Prevent it next time
Use controlled fixtures and document remaining nondeterminism.

2 practice exercises

1. Does one successful gradient check prove a custom operation is correct everywhere?

Show worked solution

No. It supports the tested input and tolerance. Check other shapes and values, investigate boundaries, and compare forward behavior with an independent reference.

2. A check fails only when the input is exactly at a nondifferentiable point. What next?

Show worked solution

Verify expected boundary behavior separately and test nearby differentiable points. Avoid treating a finite-difference failure at the boundary as automatic proof that every gradient is wrong.

Key takeaways

  • Gradient checking compares numerical and automatic derivatives.
  • Use controlled precision, values, and tolerances.
  • A passing fixture is evidence, not a universal proof.

Official references