pangolin.interface.Interface.vjp

Contents

pangolin.interface.Interface.vjp#

static Interface.vjp(fun, argnum=0)#

A combinator that returns a function building a vector-Jacobian product.

vjp(fun, argnum)(cotangent, *args, **kwargs) differentiates with respect to one positional argument of fun, which must be an RV. For real-valued inputs and outputs, the result is the gradient of the sum of the elementwise product of fun’s output and cotangent. The cotangent’s own dependencies do not contribute to this differentiation. The function must return one RV and must not create contributing random nodes. Arguments and captures may themselves be random RVs: their upstream graphs are not differentiated. Other arguments and captures are independent of the selected argument for differentiation, even when they refer to the same RV.

The function is traced once. Reverse traversal builds per-Op ir.VJP nodes and adds contributions where paths meet, without introducing a Composite. The resulting graph is connected back to the original arguments. Newly created nodes that do not contribute to the output are ignored.

Parameters:
  • fun (Callable[[P], RV]) – Function returning one RV. Contributing newly created nodes must be deterministic. Returning the selected argument or another existing RV is allowed.

  • argnum (int) – Nonnegative index of the positional RV argument to differentiate. Other arguments may have any Python or PyTree structure accepted by fun; no inputs are coerced.

Returns:

vjp_fun – Function taking a positional-only cotangent RV followed by fun’s arguments. The cotangent must have exactly the output’s shape, without coercion or broadcasting. Returns one RV with the selected argument’s shape. An unused argument gives zeros; an identity function gives the cotangent’s value.

Raises:
  • TypeError – If argnum is not an integer, the cotangent or selected argument is not an RV, or the output is not a single RV.

  • ValueError – If argnum is negative or missing from fun’s positional arguments, the cotangent has the wrong shape, or the contributing computation contains newly created random RVs.

Return type:

Callable[[Concatenate[RV, P]], RV]

Notes

RVs representing calculations in fun retain their interfaces. New VJP, accumulation, and zero nodes use the function output’s interface. Existing inputs, captures, and the supplied cotangent retain their interfaces. The returned RV always has the function output’s interface; an Identity node adapts it when necessary.

Examples

>>> def square(x):
...     return ir.RV(ir.Mul(), x, x)
>>> derivative = vjp(square)
>>> x = ir.RV(ir.Constant(3.0))
>>> cotangent = ir.RV(ir.Constant(2.0))
>>> result = derivative(cotangent, x)
>>> result.op
Add()
>>> [parent.op for parent in result.parents]
[VJP(Mul(), 0), VJP(Mul(), 1)]
>>> result.parents[0].parents[1:] == (x, x)
True