S-exp GPU
All pages
Docs · Function transformsMarkdown

Compute a value and its tree gradient

(value-and-grad function :argnums 0 :has-aux false) returns a function with the same arguments as function. One call returns (values value gradient), with one primal evaluation. Argument selection, unused leaves and shared-leaf rules are the same as grad.

sexpgpu probe --expr '(multiple-value-bind (v g) ((value-and-grad (lambda (x) (* x x))) (full [] 3.0)) (values v g))' --max-elements 100

The results are 9.0 and 6.0.

For :has-aux true, write (values scalar auxiliary) in the original function. The transformed result is (values (list scalar auxiliary) gradient):

(multiple-value-bind (result gradient)
    ((value-and-grad
       (lambda (x) (values (* x x) (list :prediction x)))
       :has-aux true)
     (full [] 3.0))
  (values (first result) (getf (second result) :prediction) gradient))

This returns 9.0, 3.0 and 6.0. Returning auxiliary data does not register a metric; report it outside the transformed function.