pub fn custom_vjp<B: Backend, I: Tree<B>, O: Tree<B>, R: Tree<B>>(
f: impl Fn(I) -> O,
fwd: impl Fn(I) -> (O, R),
bwd: impl Fn(R, O) -> I,
primals: I,
) -> OExpand description
f(primals), whose derivative in reverse mode is given by fwd and
bwd, like jax.custom_vjp.
fwd returns the outputs and residuals R; bwd takes the residuals
and the cotangents of the outputs, and returns the cotangents of the
primals. bwd must not capture traced values (return them from fwd).
Forward-mode differentiation of the result is not supported, as in JAX.
ยงExamples
use ruxla_core::{F32, Trace, grad, lax};
// The identity in the forward pass, with gradients clipped to [-1, 1].
fn clip_gradient<B: ruxla_core::Backend>(x: F32<B>) -> F32<B> {
lax::custom_vjp(|x| x, |x| (x, ()), |(), g: F32<B>| g.max(-1.0).min(1.0), x)
}
let g = grad(|x: F32<Trace>, (): ()| clip_gradient(x * 3.0)).call(&F32::new(1.0), &());
assert_eq!(g.value(), 3.0); // 3 * clip(1)