Skip to main content

ruxla_prims/
ad.rs

1//! Helpers for differentiation rules, shared by the primitives and the
2//! drivers in `ruxla-transforms`.
3//!
4//! The rules follow JAX's (`jax._src.lax`), so that ruxla's derivatives
5//! compute the same as JAX's.
6
7use ruxla_ir::ad::{AdCx, Tangent};
8use ruxla_ir::{AVal, Atom, DType, Error, HostArray, Literal, Params, Prim, Result, Shape, Value};
9
10use crate::elementwise::{ADD, CONVERT_ELEMENT_TYPE, MUL, NEG, SUB};
11use crate::structural::BROADCAST_IN_DIM;
12
13/// Applies a primitive with one output.
14pub fn bind1(cx: &mut dyn AdCx, prim: Prim, inputs: &[Atom], params: Params) -> Result<Atom> {
15    let mut outputs = cx.bind(prim, inputs, params)?;
16    if outputs.len() != 1 {
17        return Err(Error::Malformed(format!(
18            "{} returned {} outputs, expected one",
19            prim.name(),
20            outputs.len()
21        )));
22    }
23    Ok(outputs.remove(0))
24}
25
26/// A scalar literal of a type.
27pub fn scalar(dtype: DType, value: Value) -> Atom {
28    Atom::Lit(Literal::new(HostArray::full(Shape::scalar(), dtype, value)))
29}
30
31/// A scalar `value` broadcast to `aval`.
32///
33/// # Errors
34///
35/// Returns an error if the broadcast fails (it does not for valid avals).
36pub fn full(cx: &mut dyn AdCx, aval: &AVal, value: Value) -> Result<Atom> {
37    let s = scalar(aval.dtype, value);
38    if aval.shape.rank() == 0 {
39        return Ok(s);
40    }
41    bind1(
42        cx,
43        BROADCAST_IN_DIM,
44        &[s],
45        Params::BroadcastInDim {
46            shape: aval.shape.clone(),
47            broadcast_dimensions: Vec::new(),
48        },
49    )
50}
51
52/// Zeros of an abstract value.
53///
54/// # Errors
55///
56/// See [`full`].
57pub fn zeros(cx: &mut dyn AdCx, aval: &AVal) -> Result<Atom> {
58    full(cx, aval, Value::Int(0))
59}
60
61/// The tangent as an atom, with zeros of `aval` for a symbolic zero.
62///
63/// # Errors
64///
65/// See [`full`].
66pub fn instantiate(cx: &mut dyn AdCx, t: &Tangent, aval: &AVal) -> Result<Atom> {
67    match t {
68        Some(a) => Ok(a.clone()),
69        None => zeros(cx, aval),
70    }
71}
72
73/// The sum of two tangents of the same type, skipping symbolic zeros.
74///
75/// # Errors
76///
77/// Returns an error if the types differ.
78pub fn add_tangents(cx: &mut dyn AdCx, a: Tangent, b: Tangent) -> Result<Tangent> {
79    Ok(match (a, b) {
80        (None, t) | (t, None) => t,
81        (Some(a), Some(b)) => Some(bind1(cx, ADD, &[a, b], Params::None)?),
82    })
83}
84
85/// `a * b`, where `b` may be a symbolic zero.
86///
87/// # Errors
88///
89/// Returns an error if the types differ.
90pub fn mul_tangent(cx: &mut dyn AdCx, t: &Tangent, by: &Atom) -> Result<Tangent> {
91    t.as_ref()
92        .map(|t| bind1(cx, MUL, &[t.clone(), by.clone()], Params::None))
93        .transpose()
94}
95
96/// `-t`, skipping symbolic zeros.
97///
98/// # Errors
99///
100/// Returns an error if the primitive rejects the input.
101pub fn neg_tangent(cx: &mut dyn AdCx, t: &Tangent) -> Result<Tangent> {
102    t.as_ref()
103        .map(|t| bind1(cx, NEG, std::slice::from_ref(t), Params::None))
104        .transpose()
105}
106
107/// `a - b` for tangents, skipping symbolic zeros.
108///
109/// # Errors
110///
111/// Returns an error if the types differ.
112pub fn sub_tangents(cx: &mut dyn AdCx, a: Tangent, b: Tangent) -> Result<Tangent> {
113    Ok(match (a, b) {
114        (t, None) => t,
115        (None, Some(b)) => Some(bind1(cx, NEG, &[b], Params::None)?),
116        (Some(a), Some(b)) => Some(bind1(cx, SUB, &[a, b], Params::None)?),
117    })
118}
119
120/// Converts to another type (a no-op for the same type).
121///
122/// # Errors
123///
124/// Returns an error if the conversion is rejected.
125pub fn convert(cx: &mut dyn AdCx, x: &Atom, dtype: DType) -> Result<Atom> {
126    if x.aval().dtype == dtype {
127        return Ok(x.clone());
128    }
129    bind1(
130        cx,
131        CONVERT_ELEMENT_TYPE,
132        std::slice::from_ref(x),
133        Params::Convert { new_dtype: dtype },
134    )
135}
136
137/// Whether an abstract value has nonzero tangents (floats only).
138pub fn differentiable(aval: &AVal) -> bool {
139    ruxla_ir::ad::is_differentiable(aval)
140}