Skip to main content

jvp

Function jvp 

Source
pub fn jvp(
    f: &Function,
    nonzero: &[bool],
    instantiate: &[bool],
) -> Result<(Function, Vec<bool>)>
Expand description

Differentiates f in forward mode.

The result takes the inputs of f, then a tangent for each input marked nonzero, and returns the outputs of f, then the tangents of the outputs it reports as nonzero (the second result). instantiate[i] makes the tangent of output i nonzero (zeros if it does not depend on the input tangents). Only floats have tangents.

§Errors

Returns an error if a primitive that the tangents reach has no JVP rule, or if a non-float input is marked nonzero.

§Examples

use ruxla_ir::{AVal, Atom, DType, Eqn, Function, HostArray, Params, Var};

// f(x) = sin(x); its JVP is (sin(x), cos(x) * t).
let x = Var::new(AVal::scalar(DType::F32));
let y = Var::new(AVal::scalar(DType::F32));
let f = Function {
    invars: vec![x.clone()],
    eqns: vec![Eqn { prim: ruxla_prims::SIN, inputs: vec![Atom::Var(x)], params: Params::None, outputs: vec![y.clone()], loc: None }],
    outvars: vec![Atom::Var(y)],
    ..Function::default()
};
let (g, nonzero) = ruxla_transforms::jvp(&f, &[true], &[true]).unwrap();
assert_eq!(nonzero, [true]);
let out = ruxla_interp::eval(&g, &[HostArray::scalar(0.5f32), HostArray::scalar(2.0f32)]).unwrap();
assert_eq!(out[1].as_slice::<f32>().unwrap()[0], 0.5f32.cos() * 2.0);