gradgradcheck
→boolgradgradcheck(func: Callable[..., Tensor | tuple[Tensor, ...]], inputs: Sequence[Tensor], grad_outputs: Sequence[Tensor] | None = None, eps: float = 1e-06, atol: float = 1e-05, rtol: float = 0.001, raise_exception: bool = True)Verify second-order gradients via finite differences.
Most bugs in custom lucid.autograd.Function.backward
implementations show up at the second-derivative level —
the first-order gradient is consistent but the gradient of
the gradient is not. gradgradcheck constructs such a
test by wrapping func in a scalar-valued helper
differentiates it analytically with
create_graph=True, and then runs gradcheck on
so its gradient is compared against the
central finite-difference estimate
Disagreement signals a bug in the analytic backward
formula that ordinary gradcheck would miss.
Parameters
funccallableTensor inputs to a Tensor (or
tuple of Tensor). Must be twice differentiable.inputssequence of Tensorgrad_outputssequence of Tensor or None= Noneones_like
upstream gradients are always used.epsfloat= 1e-06gradcheck. Defaults to 1e-6.atolfloat= 1e-051e-5.rtolfloat= 0.0011e-3.raise_exceptionbool= TrueTrue (default) raise AssertionError on
mismatch; if False return False silently.Returns
boolTrue iff all second-order gradients agree with the
finite-difference reference within the supplied
tolerances.
Notes
The bound on the truncation error of central differences is
so tightening eps improves accuracy until round-off
error dominates.
Examples
>>> import lucid
>>> from lucid.autograd import gradgradcheck
>>> x = lucid.randn(3, requires_grad=True, dtype=lucid.float64)
>>> def f(x):
... return (x ** 3).sum()
>>> gradgradcheck(f, [x])
True