Skip to main content

ruxla_core/
transform.rs

1//! Tracing programs into IR, and running the IR.
2
3use ruxla_ir::{AVal, Function, HostArray};
4
5use crate::backend::{Backend, Native, Trace};
6use crate::trace::trace_function;
7use crate::tree::{Tree, TreeDef, leaves};
8
9/// A traced program: the IR and the structures of its input and output.
10#[derive(Clone, Debug)]
11pub struct Traced {
12    /// The IR. Its inputs are the leaves of the input, in order.
13    pub function: Function,
14    /// The structure of the input.
15    pub in_def: TreeDef,
16    /// The structure of the output.
17    pub out_def: TreeDef,
18}
19
20/// Traces `f` on `Trace` values shaped like `example` (a `Native` pytree)
21/// and returns the IR with the structures of the input and output.
22///
23/// # Panics
24///
25/// Panics if `f` uses traced values of another trace that is still in
26/// progress (a function traced at the top level cannot capture values).
27pub fn trace<I: Tree<Native>, O: Tree<Trace>>(
28    f: impl FnOnce(I::On<Trace>) -> O,
29    example: &I,
30) -> Traced {
31    let (traced, _) = trace_with_output(f, example);
32    traced
33}
34
35pub(crate) fn trace_with_output<I: Tree<Native>, O: Tree<Trace>>(
36    f: impl FnOnce(I::On<Trace>) -> O,
37    example: &I,
38) -> (Traced, O) {
39    let in_avals: Vec<AVal> = leaves(example).iter().map(Native::leaf_aval).collect();
40    let mut out: Option<O> = None;
41    let t = trace_function(&in_avals, |args| {
42        let input = example.rebuild::<Trace>(&mut args.iter().copied());
43        let o = f(input);
44        let l = leaves(&o);
45        out = Some(o);
46        l
47    });
48    assert!(
49        t.captured.is_empty(),
50        "a program traced at the top level cannot use values of another trace"
51    );
52    let out = out.expect("the function was called");
53    let traced = Traced {
54        function: t.function,
55        in_def: example.def(),
56        out_def: out.def(),
57    };
58    (traced, out)
59}
60
61/// Returns the IR of `f` traced on values shaped like `example`, like
62/// `jax.make_jaxpr`.
63///
64/// # Examples
65///
66/// ```
67/// use ruxla_core::{F32, Trace, make_ir};
68///
69/// let ir = make_ir(|x: F32<Trace>| (x * 2.0).sin(), &F32::new(1.0));
70/// assert_eq!(
71///     ir.to_string(),
72///     "{ lambda ; a:f32[]. let\n    b:f32[] = mul a 2.0:f32[]\n    c:f32[] = sin b\n  in (c,) }"
73/// );
74/// ```
75pub fn make_ir<I: Tree<Native>, O: Tree<Trace>>(
76    f: impl FnOnce(I::On<Trace>) -> O,
77    example: &I,
78) -> Function {
79    trace(f, example).function
80}
81
82/// Traces `f` and runs the IR with the interpreter on `input`, returning
83/// the output as `Native` values. Useful to check that a program gives the
84/// same results natively and as IR.
85///
86/// # Panics
87///
88/// Panics if the interpreter fails, which indicates a bug.
89pub fn interpret<I: Tree<Native>, O: Tree<Trace>>(
90    f: impl FnOnce(I::On<Trace>) -> O,
91    input: &I,
92) -> O::On<Native> {
93    let (traced, out) = trace_with_output(f, input);
94    let args = leaves(input);
95    let outs: Vec<HostArray> =
96        ruxla_interp::eval(&traced.function, &args).unwrap_or_else(|e| panic!("{e}"));
97    out.rebuild::<Native>(&mut outs.into_iter())
98}