Skip to main content

ruxla_ir/
ad.rs

1//! The interface for automatic differentiation.
2//!
3//! Differentiation follows JAX: forward mode applies each primitive's JVP
4//! rule ([`Primitive::jvp`]), which computes the tangents of the outputs with
5//! operations that are linear in the tangents of the inputs; reverse mode
6//! linearizes (JVP followed by partial evaluation, which separates the
7//! primal computation from the linear tangent computation) and transposes
8//! the linear part with each primitive's transpose rule
9//! ([`Primitive::transpose`]). Rules emit operations through [`AdCx`]; the
10//! drivers live in `ruxla-transforms`.
11//!
12//! [`Primitive::jvp`]: crate::Primitive::jvp
13//! [`Primitive::transpose`]: crate::Primitive::transpose
14
15use crate::error::Result;
16use crate::function::{Atom, Function, Params};
17use crate::host::HostArray;
18use crate::primitive::Prim;
19use crate::shape::AVal;
20
21/// A tangent or a cotangent: `None` is a symbolic zero, which rules skip
22/// instead of computing with zeros.
23pub type Tangent = Option<Atom>;
24
25/// The body given to [`AdCx::build_function`].
26pub type AdBuildBody<'a> = dyn FnMut(&mut dyn AdCx, &[Atom]) -> Result<Vec<Atom>> + 'a;
27
28/// An input of a primitive being transposed.
29#[derive(Clone, Debug, PartialEq)]
30pub enum TransposeInput {
31    /// An input that depends linearly on the variables being transposed:
32    /// its value is not known, only its type.
33    Linear(AVal),
34    /// An input that does not depend on them (a residual or a constant).
35    Const(Atom),
36}
37
38impl TransposeInput {
39    /// The abstract value of the input.
40    pub fn aval(&self) -> AVal {
41        match self {
42            TransposeInput::Linear(a) => a.clone(),
43            TransposeInput::Const(x) => x.aval(),
44        }
45    }
46
47    /// Whether the input is linear.
48    pub fn is_linear(&self) -> bool {
49        matches!(self, TransposeInput::Linear(_))
50    }
51
52    /// The value of a constant input.
53    ///
54    /// # Panics
55    ///
56    /// Panics if the input is linear.
57    #[track_caller]
58    pub fn constant(&self) -> &Atom {
59        match self {
60            TransposeInput::Const(x) => x,
61            TransposeInput::Linear(_) => panic!("a linear input has no value"),
62        }
63    }
64}
65
66/// A context that emits the operations of a differentiated function.
67pub trait AdCx {
68    /// Applies a primitive and returns its outputs.
69    ///
70    /// # Errors
71    ///
72    /// Returns an error if the primitive rejects the inputs.
73    fn bind(&mut self, prim: Prim, inputs: &[Atom], params: Params) -> Result<Vec<Atom>>;
74
75    /// Returns an atom holding a constant array.
76    fn constant(&mut self, value: HostArray) -> Atom;
77
78    /// Builds a new function with inputs `in_avals` from the operations that
79    /// `body` emits through the context it receives. Atoms of this context
80    /// must not be used inside `body`.
81    ///
82    /// # Errors
83    ///
84    /// Returns an error from `body`.
85    fn build_function(&mut self, in_avals: &[AVal], body: &mut AdBuildBody<'_>)
86    -> Result<Function>;
87
88    /// Differentiates a nested function (the body of `cond`, `scan`, ...)
89    /// in forward mode.
90    ///
91    /// The result takes the primal inputs, then the tangents of the inputs
92    /// marked `nonzero`, and returns the primal outputs, then the tangents
93    /// of the outputs it reports as nonzero. `instantiate[i]` makes the
94    /// tangent of output `i` nonzero (with zeros if needed).
95    ///
96    /// # Errors
97    ///
98    /// Returns an error if a primitive of `f` has no JVP rule.
99    fn jvp_function(
100        &mut self,
101        f: &Function,
102        nonzero: &[bool],
103        instantiate: &[bool],
104    ) -> Result<(Function, Vec<bool>)>;
105
106    /// Transposes a nested function that is linear in the inputs marked
107    /// `linear`.
108    ///
109    /// The result takes the other inputs, then a cotangent for every output,
110    /// and returns the cotangents of the linear inputs (zeros where they do
111    /// not depend on the outputs).
112    ///
113    /// # Errors
114    ///
115    /// Returns an error if a primitive of `f` that the linear inputs reach
116    /// has no transpose rule.
117    fn transpose_function(&mut self, f: &Function, linear: &[bool]) -> Result<Function>;
118}
119
120/// Whether values of an abstract value have (nonzero) tangents: only floats
121/// and complex numbers do; tangents of integers and booleans are always
122/// zero.
123pub fn is_differentiable(aval: &AVal) -> bool {
124    aval.dtype.is_inexact()
125}