All pages
Differentiate a function over a tree
(grad function :argnums 0 :has-aux false) returns a function. Calling it with
the original arguments returns the gradient tree for the selected argument. The
differentiated argument is a fixed tensor/list/vector/plist tree with float
leaves; the result preserves its structure, keys, shapes and shared leaves.
Unused leaves receive zeros. The differentiated function must return a scalar
float tensor of shape [].
A probe returns tensors, so extract a leaf when inspecting a tree:
sexpgpu probe --expr '(getf ((grad (lambda (p) (* (getf p :x) (getf p :x)))) (list :x (full [] 3.0))) :x)' --max-elements 100The result is 6.0.
argnums is a nonnegative static index, or a nonempty vector of distinct
indices. A vector selects multiple arguments and returns a vector of their
gradient trees in the specified order. Argument positions remain independent
even if the same tensor is passed twice. Repeated leaves within one argument are
tied and accumulate one shared gradient.
With :has-aux true, the function returns (values scalar auxiliary) and the
gradient function returns (values gradient auxiliary). Auxiliary values do not
contribute to this derivative. Use value-and-grad when the
primal value is also needed.
Nested grad, and grad both inside and around scan, are
supported. Declarations and reporting effects are refused with
E-TRANSFORM-003; invalid result/kind contracts use E-TRANSFORM-002.
E-TRANSFORM-004 names a derivative operation that cannot be transformed. There
is no function evaluation on the host during a training step.