Skip to main content

Crate chainrules_core

Crate chainrules_core 

Source
Expand description

Backend-agnostic contracts for custom automatic-differentiation rules.

chainrules-core is intentionally not an AD engine. It defines a small protocol through which numerical packages publish operation-aware Jacobian-vector product (JVP) and vector-Jacobian product (VJP) rules. Backends may consume those rules without either side depending on the other.

Version 0.2 specifies distinct tangent and cotangent associations, typed failure for both primal and reverse computations, and one-shot pullback ownership. See the repository’s PROTOCOL.md and MIGRATION.md for the complete semantic contract and the migration from 0.1.

§Example

use std::convert::Infallible;

use chainrules_core::{JvpRule, Pullback, VjpRule};

struct Scale(f64);
struct ScalePullback(f64);

impl JvpRule<f64> for Scale {
    type Output = f64;
    type Error = Infallible;

    fn jvp(&self, x: &f64, dx: &f64) -> Result<(f64, f64), Self::Error> {
        Ok((self.0 * x, self.0 * dx))
    }
}

impl Pullback<f64, f64> for ScalePullback {
    type Error = Infallible;

    fn apply(self, cotangent: f64) -> Result<f64, Self::Error> {
        Ok(self.0 * cotangent)
    }
}

impl VjpRule<f64> for Scale {
    type Output = f64;
    type Error = Infallible;
    type Pullback<'a> = ScalePullback;

    fn vjp<'a>(
        &'a self,
        x: &'a f64,
    ) -> Result<(f64, Self::Pullback<'a>), Self::Error> {
        Ok((self.0 * x, ScalePullback(self.0)))
    }
}

let rule = Scale(3.0);
assert_eq!(rule.jvp(&2.0, &0.5).unwrap(), (6.0, 1.5));
let (value, pullback) = rule.vjp(&2.0).unwrap();
assert_eq!((value, pullback.apply(0.25).unwrap()), (6.0, 0.75));

Modules§

testing
Numerical conformance helpers for custom rules.

Structs§

NoTangent
Marks a primal value with no differentiable input space.

Traits§

Differentiable
Associates a primal value with its forward tangent and reverse cotangent representations.
JvpRule
A forward-mode rule computing a primal output and a Jacobian-vector product.
Pullback
A one-shot reverse-mode pullback.
VjpRule
A reverse-mode rule computing a primal output and a one-shot pullback.