Skip to main content

ruxla_core/
grad.rs

1//! Automatic differentiation: `grad`, `value_and_grad`, `jvp`, and `vjp`.
2//!
3//! The functions take and return pytrees of [`Trace`] values; they are
4//! traced, differentiated by `ruxla-transforms` (JAX's rules), and run with
5//! the interpreter (`call`), with XLA (`call_xla`), or inside another trace
6//! (`call_traced`, which adds the derivative to the outer IR as a `jit`
7//! equation, so that `jit(|..| grad(f).call_traced(..))` compiles the whole
8//! training step).
9
10use std::fmt;
11use std::sync::Arc;
12
13use ruxla_ir::{AVal, Function, HostArray, Params};
14use ruxla_pjrt::Buffer;
15
16use crate::backend::{Backend, Native, Trace};
17use crate::runtime::{self, Error};
18use crate::trace::{self, TraceRef, trace_function};
19use crate::tree::{Tree, leaves};
20
21/// Returns a function that computes `f(params, args)` and its gradient with
22/// respect to `params`, like `jax.value_and_grad(f, has_aux=True)`.
23///
24/// `f` takes the parameters (a pytree of float values, which are
25/// differentiated) and other arguments (which are not), and returns a
26/// pytree whose first leaf is the loss, a float scalar. The other leaves are
27/// auxiliary values, returned as they are. The gradient has the structure of
28/// the parameters.
29///
30/// # Examples
31///
32/// ```
33/// use ruxla_core::{F32, Trace, value_and_grad};
34///
35/// // d/dx (x * x * y) = 2 * x * y
36/// let f = value_and_grad(|x: F32<Trace>, y: F32<Trace>| x * x * y);
37/// let (value, grad) = f.call(&F32::new(3.0), &F32::new(2.0));
38/// assert_eq!((value.value(), grad.value()), (18.0, 12.0));
39/// ```
40pub fn value_and_grad<F>(f: F) -> ValueAndGrad<F> {
41    ValueAndGrad { f }
42}
43
44/// Returns a function that computes the gradient of `f(params, args)` with
45/// respect to `params`, like `jax.grad`. See [`value_and_grad`] for what `f`
46/// takes and returns (auxiliary outputs are dropped).
47///
48/// # Examples
49///
50/// ```
51/// use ruxla_core::{F32, Trace, grad};
52///
53/// let g = grad(|x: F32<Trace>, (): ()| x.sin());
54/// assert_eq!(g.call(&F32::new(0.0), &()).value(), 1.0);
55/// ```
56pub fn grad<F>(f: F) -> Grad<F> {
57    Grad {
58        inner: ValueAndGrad { f },
59    }
60}
61
62/// See [`value_and_grad`].
63pub struct ValueAndGrad<F> {
64    f: F,
65}
66
67/// See [`grad`].
68pub struct Grad<F> {
69    inner: ValueAndGrad<F>,
70}
71
72impl<F> fmt::Debug for ValueAndGrad<F> {
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74        f.debug_struct("ValueAndGrad").finish_non_exhaustive()
75    }
76}
77
78impl<F> fmt::Debug for Grad<F> {
79    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80        f.debug_struct("Grad").finish_non_exhaustive()
81    }
82}
83
84/// A derivative traced for some inputs: the IR, the leaves of its inputs,
85/// and the output of tracing (for the structure of the results).
86struct Derived<O> {
87    function: Function,
88    args: Vec<HostArray>,
89    out: O,
90}
91
92/// Traces `f(a, b)` on values shaped like `a` and `b`; the IR takes the
93/// values captured from outer traces (none at the top level), then the
94/// leaves of `a`, then those of `b`.
95fn trace2<A, B, O>(
96    f: impl FnOnce(A, B) -> O,
97    a_avals: &[AVal],
98    b_avals: &[AVal],
99    a: impl FnOnce(&mut dyn Iterator<Item = TraceRef>) -> A,
100    b: impl FnOnce(&mut dyn Iterator<Item = TraceRef>) -> B,
101) -> (trace::Traced, O)
102where
103    O: Tree<Trace>,
104{
105    let mut in_avals = a_avals.to_vec();
106    in_avals.extend_from_slice(b_avals);
107    let mut out: Option<O> = None;
108    let t = trace_function(&in_avals, |refs| {
109        let mut it = refs.iter().copied();
110        let x = a(&mut it);
111        let y = b(&mut it);
112        let o = f(x, y);
113        let l = leaves(&o);
114        out = Some(o);
115        l
116    });
117    (t, out.expect("the function was called"))
118}
119
120fn native_avals<T: Tree<Native>>(x: &T) -> Vec<AVal> {
121    leaves(x).iter().map(Native::leaf_aval).collect()
122}
123
124fn trace_avals<T: Tree<Trace>>(x: &T) -> Vec<AVal> {
125    leaves(x).iter().map(|&r| trace::aval(r)).collect()
126}
127
128/// The mask of the inputs differentiated: `n` after `skip`, of `total`.
129fn mask(skip: usize, n: usize, total: usize) -> Vec<bool> {
130    (0..total).map(|i| i >= skip && i < skip + n).collect()
131}
132
133fn check_float(avals: &[AVal], what: &str) {
134    for a in avals {
135        assert!(
136            a.dtype.is_inexact(),
137            "{what}: differentiated values must be floats or complex numbers, got {a}"
138        );
139    }
140}
141
142/// Runs `f` with the interpreter.
143fn interpret(f: &Function, args: &[HostArray]) -> Vec<HostArray> {
144    ruxla_interp::eval(f, args).unwrap_or_else(|e| panic!("{e}"))
145}
146
147/// Runs `f` with XLA.
148fn execute_xla(f: &Function, args: &[HostArray]) -> Result<Vec<HostArray>, Error> {
149    let platform = runtime::platform();
150    let client = runtime::client(platform)?;
151    let exe = runtime::compile(platform, f)?;
152    let buffers = args
153        .iter()
154        .map(|a| client.buffer_from_host_array(a))
155        .collect::<Result<Vec<_>, _>>()?;
156    let outs = exe.execute(&buffers.iter().collect::<Vec<_>>())?;
157    Ok(outs
158        .iter()
159        .map(Buffer::to_host_array)
160        .collect::<Result<Vec<_>, _>>()?)
161}
162
163/// Adds `f` applied to `inputs` to the current trace as a `jit` equation.
164fn bind_function(name: &str, f: Function, inputs: &[TraceRef]) -> Vec<TraceRef> {
165    trace::bind(
166        ruxla_prims::JIT,
167        inputs,
168        Params::Jit {
169            name: String::from(name),
170            body: Arc::new(f),
171        },
172    )
173}
174
175impl<F> ValueAndGrad<F> {
176    fn derive<P, A, O>(&self, params: &P, args: &A) -> Derived<O>
177    where
178        P: Tree<Native>,
179        A: Tree<Native>,
180        O: Tree<Trace>,
181        F: Fn(P::On<Trace>, A::On<Trace>) -> O,
182    {
183        let (pa, aa) = (native_avals(params), native_avals(args));
184        check_float(&pa, "grad");
185        let (t, out) = trace2(
186            &self.f,
187            &pa,
188            &aa,
189            |it| params.rebuild::<Trace>(it),
190            |it| args.rebuild::<Trace>(it),
191        );
192        assert!(
193            t.captured.is_empty(),
194            "a program traced at the top level cannot use values of another trace"
195        );
196        let wrt = mask(0, pa.len(), pa.len() + aa.len());
197        let function = ruxla_transforms::value_and_grad(&t.function, &wrt)
198            .unwrap_or_else(|e| panic!("grad: {e}"));
199        let mut all = leaves(params);
200        all.extend(leaves(args));
201        Derived {
202            function,
203            args: all,
204            out,
205        }
206    }
207
208    fn split<P, O>(d: &Derived<O>, params: &P, outs: Vec<HostArray>) -> (O::On<Native>, P)
209    where
210        P: Tree<Native>,
211        O: Tree<Trace>,
212    {
213        let mut it = outs.into_iter();
214        let value = d.out.rebuild::<Native>(&mut it);
215        (value, params.unflatten_like(&mut it))
216    }
217
218    /// Computes the value and the gradient with the interpreter.
219    ///
220    /// # Panics
221    ///
222    /// Panics if a parameter is not a float, if the first output is not a
223    /// float scalar, or if a primitive has no differentiation rule.
224    #[track_caller]
225    pub fn call<P, A, O>(&self, params: &P, args: &A) -> (O::On<Native>, P)
226    where
227        P: Tree<Native>,
228        A: Tree<Native>,
229        O: Tree<Trace>,
230        F: Fn(P::On<Trace>, A::On<Trace>) -> O,
231    {
232        let d = self.derive(params, args);
233        let outs = interpret(&d.function, &d.args);
234        Self::split(&d, params, outs)
235    }
236
237    /// Computes the value and the gradient with XLA.
238    ///
239    /// # Errors
240    ///
241    /// Returns an error if no PJRT plugin is configured, or if compiling or
242    /// running fails.
243    ///
244    /// # Panics
245    ///
246    /// See [`ValueAndGrad::call`].
247    pub fn call_xla<P, A, O>(&self, params: &P, args: &A) -> Result<(O::On<Native>, P), Error>
248    where
249        P: Tree<Native>,
250        A: Tree<Native>,
251        O: Tree<Trace>,
252        F: Fn(P::On<Trace>, A::On<Trace>) -> O,
253    {
254        let d = self.derive(params, args);
255        let outs = execute_xla(&d.function, &d.args)?;
256        Ok(Self::split(&d, params, outs))
257    }
258
259    /// Computes the value and the gradient inside another trace: the
260    /// derivative becomes a `jit` equation of the outer IR. Values that `f`
261    /// captures from the outer trace are not differentiated.
262    ///
263    /// # Panics
264    ///
265    /// See [`ValueAndGrad::call`].
266    pub fn call_traced<P, A, O>(&self, params: P, args: A) -> (O, P)
267    where
268        P: Tree<Trace>,
269        A: Tree<Trace>,
270        O: Tree<Trace>,
271        F: Fn(P, A) -> O,
272    {
273        let (pa, aa) = (trace_avals(&params), trace_avals(&args));
274        check_float(&pa, "grad");
275        let (t, out) = trace2(
276            &self.f,
277            &pa,
278            &aa,
279            |it| params.unflatten_like(it),
280            |it| args.unflatten_like(it),
281        );
282        let ncap = t.captured.len();
283        let wrt = mask(ncap, pa.len(), ncap + pa.len() + aa.len());
284        let function = ruxla_transforms::value_and_grad(&t.function, &wrt)
285            .unwrap_or_else(|e| panic!("grad: {e}"));
286        let mut inputs = t.captured;
287        inputs.extend(leaves(&params));
288        inputs.extend(leaves(&args));
289        let outs = bind_function("value_and_grad", function, &inputs);
290        let mut it = outs.into_iter();
291        let value = out.unflatten_like(&mut it);
292        (value, params.unflatten_like(&mut it))
293    }
294
295    /// Returns the IR of the derivative for inputs shaped like `params` and
296    /// `args`: the outputs of `f`, then the gradient.
297    ///
298    /// # Panics
299    ///
300    /// See [`ValueAndGrad::call`].
301    pub fn make_ir<P, A, O>(&self, params: &P, args: &A) -> Function
302    where
303        P: Tree<Native>,
304        A: Tree<Native>,
305        O: Tree<Trace>,
306        F: Fn(P::On<Trace>, A::On<Trace>) -> O,
307    {
308        self.derive(params, args).function
309    }
310}
311
312impl<F> Grad<F> {
313    /// Computes the gradient with the interpreter.
314    ///
315    /// # Panics
316    ///
317    /// See [`ValueAndGrad::call`].
318    #[track_caller]
319    pub fn call<P, A, O>(&self, params: &P, args: &A) -> P
320    where
321        P: Tree<Native>,
322        A: Tree<Native>,
323        O: Tree<Trace>,
324        F: Fn(P::On<Trace>, A::On<Trace>) -> O,
325    {
326        self.inner.call(params, args).1
327    }
328
329    /// Computes the gradient with XLA.
330    ///
331    /// # Errors
332    ///
333    /// See [`ValueAndGrad::call_xla`].
334    pub fn call_xla<P, A, O>(&self, params: &P, args: &A) -> Result<P, Error>
335    where
336        P: Tree<Native>,
337        A: Tree<Native>,
338        O: Tree<Trace>,
339        F: Fn(P::On<Trace>, A::On<Trace>) -> O,
340    {
341        Ok(self.inner.call_xla(params, args)?.1)
342    }
343
344    /// Computes the gradient inside another trace; see
345    /// [`ValueAndGrad::call_traced`].
346    pub fn call_traced<P, A, O>(&self, params: P, args: A) -> P
347    where
348        P: Tree<Trace>,
349        A: Tree<Trace>,
350        O: Tree<Trace>,
351        F: Fn(P, A) -> O,
352    {
353        self.inner.call_traced(params, args).1
354    }
355}
356
357/// Returns a function that computes `f(primals)` and its derivative in the
358/// direction of `tangents` (forward mode), like `jax.jvp`.
359///
360/// Tangents of non-float inputs are ignored; tangents of non-float outputs
361/// are zeros.
362///
363/// # Examples
364///
365/// ```
366/// use ruxla_core::{F32, Trace, jvp};
367///
368/// let f = jvp(|(x, y): (F32<Trace>, F32<Trace>)| x * y);
369/// let (out, t) = f.call(&(F32::new(3.0), F32::new(2.0)), &(F32::new(1.0), F32::new(0.0)));
370/// assert_eq!((out.value(), t.value()), (6.0, 2.0));
371/// ```
372pub fn jvp<F>(f: F) -> Jvp<F> {
373    Jvp { f }
374}
375
376/// See [`jvp`].
377pub struct Jvp<F> {
378    f: F,
379}
380
381impl<F> fmt::Debug for Jvp<F> {
382    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
383        f.debug_struct("Jvp").finish_non_exhaustive()
384    }
385}
386
387/// The JVP of a traced function with every float input and output
388/// differentiated, with zeros for the tangents of non-float outputs.
389fn jvp_function(f: &Function, skip: usize) -> Function {
390    let nonzero: Vec<bool> = f
391        .invars
392        .iter()
393        .enumerate()
394        .map(|(i, v)| i >= skip && v.aval().dtype.is_inexact())
395        .collect();
396    let instantiate = vec![true; f.outvars.len()];
397    let (g, out_nonzero) =
398        ruxla_transforms::jvp(f, &nonzero, &instantiate).unwrap_or_else(|e| panic!("jvp: {e}"));
399    // Inputs: all primals, then a tangent for every input after `skip` (the
400    // non-float ones unused); outputs: primals, then a tangent for every
401    // output (zeros for the non-float ones).
402    let mut g = g;
403    let n_in = f.invars.len();
404    let tangent_vars = g.invars.split_off(n_in);
405    let mut tv = tangent_vars.into_iter();
406    for (i, v) in f.invars.iter().enumerate().skip(skip) {
407        let t = if nonzero[i] {
408            tv.next().expect("a tangent per nonzero input")
409        } else {
410            ruxla_ir::Var::new(v.aval().clone())
411        };
412        g.invars.push(t);
413    }
414    let n_out = f.outvars.len();
415    let tangents = g.outvars.split_off(n_out);
416    let mut to = tangents.into_iter();
417    for (a, nz) in f.outvars.iter().zip(out_nonzero) {
418        let t = if nz {
419            to.next().expect("a tangent per nonzero output")
420        } else {
421            let aval = a.aval();
422            ruxla_ir::Atom::Lit(ruxla_ir::Literal::new(HostArray::zeros(
423                aval.shape.clone(),
424                aval.dtype,
425            )))
426        };
427        g.outvars.push(t);
428    }
429    g
430}
431
432impl<F> Jvp<F> {
433    /// Computes the outputs and their tangents with the interpreter.
434    ///
435    /// # Panics
436    ///
437    /// Panics if the primals and tangents differ in structure or types, or
438    /// if a primitive has no JVP rule.
439    #[track_caller]
440    pub fn call<I, O>(&self, primals: &I, tangents: &I) -> (O::On<Native>, O::On<Native>)
441    where
442        I: Tree<Native>,
443        O: Tree<Trace>,
444        F: Fn(I::On<Trace>) -> O,
445    {
446        assert_eq!(
447            native_avals(primals),
448            native_avals(tangents),
449            "jvp: the tangents must have the types of the primals"
450        );
451        let (t, out) = crate::transform::trace_with_output(&self.f, primals);
452        let g = jvp_function(&t.function, 0);
453        let mut args = leaves(primals);
454        args.extend(leaves(tangents));
455        let mut it = interpret(&g, &args).into_iter();
456        let o = out.rebuild::<Native>(&mut it);
457        let t = out.rebuild::<Native>(&mut it);
458        (o, t)
459    }
460
461    /// Computes the outputs and their tangents inside another trace.
462    ///
463    /// # Panics
464    ///
465    /// See [`Jvp::call`].
466    pub fn call_traced<I, O>(&self, primals: I, tangents: I) -> (O, O)
467    where
468        I: Tree<Trace>,
469        O: Tree<Trace>,
470        F: Fn(I) -> O,
471    {
472        let pa = trace_avals(&primals);
473        assert_eq!(
474            pa,
475            trace_avals(&tangents),
476            "jvp: the tangents must have the types of the primals"
477        );
478        let (t, out) = trace2(
479            |x: I, (): ()| (self.f)(x),
480            &pa,
481            &[],
482            |it| primals.unflatten_like(it),
483            |_| (),
484        );
485        let ncap = t.captured.len();
486        let g = jvp_function(&t.function, ncap);
487        let mut inputs = t.captured;
488        inputs.extend(leaves(&primals));
489        inputs.extend(leaves(&tangents));
490        let outs = bind_function("jvp", g, &inputs);
491        let mut it = outs.into_iter();
492        let o = out.unflatten_like(&mut it);
493        let t = out.unflatten_like(&mut it);
494        (o, t)
495    }
496}
497
498/// Returns a function that computes `f(primals)` and the cotangents of the
499/// inputs for given cotangents of the outputs (reverse mode), like calling
500/// the function that `jax.vjp` returns.
501///
502/// Cotangents of non-float outputs are ignored; cotangents of non-float
503/// inputs are zeros.
504///
505/// # Examples
506///
507/// ```
508/// use ruxla_core::{F32, Trace, vjp};
509///
510/// let f = vjp(|(x, y): (F32<Trace>, F32<Trace>)| x * y);
511/// let (out, (cx, cy)) = f.call(&(F32::new(3.0), F32::new(2.0)), &F32::new(1.0));
512/// assert_eq!((out.value(), cx.value(), cy.value()), (6.0, 2.0, 3.0));
513/// ```
514pub fn vjp<F>(f: F) -> VjpFn<F> {
515    VjpFn { f }
516}
517
518/// See [`vjp`].
519pub struct VjpFn<F> {
520    f: F,
521}
522
523impl<F> fmt::Debug for VjpFn<F> {
524    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
525        f.debug_struct("VjpFn").finish_non_exhaustive()
526    }
527}
528
529/// A function of the inputs of `f` (after `skip` captured values) and a
530/// cotangent for every output, returning the outputs, then a cotangent for
531/// every input after `skip` (zeros for non-floats).
532fn vjp_function(f: &Function, skip: usize) -> Function {
533    use ruxla_ir::{Atom, Eqn, Literal, Var};
534    let wrt: Vec<bool> = f
535        .invars
536        .iter()
537        .enumerate()
538        .map(|(i, v)| i >= skip && v.aval().dtype.is_inexact())
539        .collect();
540    let v = ruxla_transforms::vjp(f, &wrt).unwrap_or_else(|e| panic!("vjp: {e}"));
541    let n_out = f.outvars.len();
542    let invars: Vec<Var> = f
543        .invars
544        .iter()
545        .map(|x| Var::new(x.aval().clone()))
546        .collect();
547    let ct_vars: Vec<Var> = f.outvars.iter().map(|a| Var::new(a.aval())).collect();
548    let fwd_outs: Vec<Var> = v.forward.out_avals().into_iter().map(Var::new).collect();
549    let mut back_inputs: Vec<Atom> = fwd_outs[n_out..].iter().cloned().map(Atom::Var).collect();
550    back_inputs.extend(
551        ct_vars
552            .iter()
553            .zip(&v.differentiable_outputs)
554            .filter(|(_, d)| **d)
555            .map(|(c, _)| Atom::Var(c.clone())),
556    );
557    let back_outs: Vec<Var> = v.backward.out_avals().into_iter().map(Var::new).collect();
558    let call = |body: Function, inputs: Vec<Atom>, outputs: Vec<Var>| Eqn {
559        prim: ruxla_prims::JIT,
560        inputs,
561        params: Params::Jit {
562            name: String::from("vjp"),
563            body: Arc::new(body),
564        },
565        outputs,
566        loc: None,
567    };
568    let eqns = vec![
569        call(
570            v.forward,
571            invars.iter().cloned().map(Atom::Var).collect(),
572            fwd_outs.clone(),
573        ),
574        call(v.backward, back_inputs, back_outs.clone()),
575    ];
576    let mut outvars: Vec<Atom> = fwd_outs[..n_out].iter().cloned().map(Atom::Var).collect();
577    let mut cts = back_outs.into_iter();
578    for (x, &w) in f.invars.iter().zip(&wrt).skip(skip) {
579        outvars.push(if w {
580            Atom::Var(cts.next().expect("a cotangent per input"))
581        } else {
582            let a = x.aval();
583            Atom::Lit(Literal::new(HostArray::zeros(a.shape.clone(), a.dtype)))
584        });
585    }
586    let mut all_invars = invars;
587    all_invars.extend(ct_vars);
588    Function {
589        constvars: Vec::new(),
590        invars: all_invars,
591        eqns,
592        outvars,
593    }
594}
595
596impl<F> VjpFn<F> {
597    /// Computes the outputs and the cotangents of the inputs with the
598    /// interpreter.
599    ///
600    /// # Panics
601    ///
602    /// Panics if the cotangents do not have the types of the outputs, or if
603    /// a primitive has no differentiation rule.
604    #[track_caller]
605    pub fn call<I, O>(&self, primals: &I, cotangents: &O::On<Native>) -> (O::On<Native>, I)
606    where
607        I: Tree<Native>,
608        O: Tree<Trace>,
609        O::On<Native>: Tree<Native>,
610        F: Fn(I::On<Trace>) -> O,
611    {
612        let (t, out) = crate::transform::trace_with_output(&self.f, primals);
613        assert_eq!(
614            t.function.out_avals(),
615            native_avals(cotangents),
616            "vjp: the cotangents must have the types of the outputs"
617        );
618        let g = vjp_function(&t.function, 0);
619        let mut args = leaves(primals);
620        args.extend(leaves(cotangents));
621        let mut it = interpret(&g, &args).into_iter();
622        let o = out.rebuild::<Native>(&mut it);
623        (o, primals.unflatten_like(&mut it))
624    }
625
626    /// Computes the outputs and the cotangents of the inputs inside another
627    /// trace.
628    ///
629    /// # Panics
630    ///
631    /// See [`VjpFn::call`].
632    pub fn call_traced<I, O>(&self, primals: I, cotangents: O) -> (O, I)
633    where
634        I: Tree<Trace>,
635        O: Tree<Trace>,
636        F: Fn(I) -> O,
637    {
638        let pa = trace_avals(&primals);
639        let (t, out) = trace2(
640            |x: I, (): ()| (self.f)(x),
641            &pa,
642            &[],
643            |it| primals.unflatten_like(it),
644            |_| (),
645        );
646        assert_eq!(
647            t.function.out_avals()[..],
648            trace_avals(&cotangents)[..],
649            "vjp: the cotangents must have the types of the outputs"
650        );
651        let ncap = t.captured.len();
652        let g = vjp_function(&t.function, ncap);
653        let mut inputs = t.captured;
654        inputs.extend(leaves(&primals));
655        inputs.extend(leaves(&cotangents));
656        let outs = bind_function("vjp", g, &inputs);
657        let mut it = outs.into_iter();
658        let o = out.unflatten_like(&mut it);
659        (o, primals.unflatten_like(&mut it))
660    }
661}