pangolin.interface.Interface.grad#
- Interface.grad(fun, argnum=0)[source]#
A gradient combinator that also accepts a selected numeric scalar.
If the selected argument is a Python or NumPy integer or floating-point scalar, it becomes a constant RV before differentiation. Booleans, complex numbers, arrays, and numeric leaves inside containers are not coerced. All other arguments are supplied unchanged. Otherwise, the contract is the same as
pangolin.functional.grad.- Parameters:
fun (Callable[[P], RV]) – Function returning one scalar RV, with no contributing newly created random nodes. The selected argument is supplied to it as an RV or an RV-only PyTree.
argnum (int) – Nonnegative index of the supplied positional argument to differentiate.
- Returns:
grad_fun – Function returning one gradient RV for a scalar or RV input, or the selected RV-only PyTree’s structure with one gradient RV per leaf.
- Return type:
Callable[[P], Any]
Notes
Newly coerced scalars use this interface; existing RVs retain their interfaces. Gradient outputs use the supplied function’s output interface.
Static typing preserves
fun’s parameter signature and usesAnyfor the gradient’s return type. Scalar coercion does not widen the advertised input types.Examples
>>> from pangolin import interface as pi >>> pi.grad(pi.exp)(0.0) RV(VJP(Exp(), 0), RV(Constant(1.)), RV(Constant(0.)))
RV-only trees continue to produce gradients with the same structure:
>>> result = pi.grad(lambda pair: pair[0] * pair[1])([pi.constant(2), pi.constant(3)]) >>> [x.shape for x in result] [(), ()]