ruxla-core 0.1.0

Internal crate of ruxla (use the `ruxla` crate): the frontend of ruxla (backend-generic values, native and tracing backends)
Documentation
//! Tracing programs into IR, and running the IR.

use ruxla_ir::{AVal, Function, HostArray};

use crate::backend::{Backend, Native, Trace};
use crate::trace::trace_function;
use crate::tree::{Tree, TreeDef, leaves};

/// A traced program: the IR and the structures of its input and output.
#[derive(Clone, Debug)]
pub struct Traced {
    /// The IR. Its inputs are the leaves of the input, in order.
    pub function: Function,
    /// The structure of the input.
    pub in_def: TreeDef,
    /// The structure of the output.
    pub out_def: TreeDef,
}

/// Traces `f` on `Trace` values shaped like `example` (a `Native` pytree)
/// and returns the IR with the structures of the input and output.
///
/// # Panics
///
/// Panics if `f` uses traced values of another trace that is still in
/// progress (a function traced at the top level cannot capture values).
pub fn trace<I: Tree<Native>, O: Tree<Trace>>(
    f: impl FnOnce(I::On<Trace>) -> O,
    example: &I,
) -> Traced {
    let (traced, _) = trace_with_output(f, example);
    traced
}

pub(crate) fn trace_with_output<I: Tree<Native>, O: Tree<Trace>>(
    f: impl FnOnce(I::On<Trace>) -> O,
    example: &I,
) -> (Traced, O) {
    let in_avals: Vec<AVal> = leaves(example).iter().map(Native::leaf_aval).collect();
    let mut out: Option<O> = None;
    let t = trace_function(&in_avals, |args| {
        let input = example.rebuild::<Trace>(&mut args.iter().copied());
        let o = f(input);
        let l = leaves(&o);
        out = Some(o);
        l
    });
    assert!(
        t.captured.is_empty(),
        "a program traced at the top level cannot use values of another trace"
    );
    let out = out.expect("the function was called");
    let traced = Traced {
        function: t.function,
        in_def: example.def(),
        out_def: out.def(),
    };
    (traced, out)
}

/// Returns the IR of `f` traced on values shaped like `example`, like
/// `jax.make_jaxpr`.
///
/// # Examples
///
/// ```
/// use ruxla_core::{F32, Trace, make_ir};
///
/// let ir = make_ir(|x: F32<Trace>| (x * 2.0).sin(), &F32::new(1.0));
/// assert_eq!(
///     ir.to_string(),
///     "{ lambda ; a:f32[]. let\n    b:f32[] = mul a 2.0:f32[]\n    c:f32[] = sin b\n  in (c,) }"
/// );
/// ```
pub fn make_ir<I: Tree<Native>, O: Tree<Trace>>(
    f: impl FnOnce(I::On<Trace>) -> O,
    example: &I,
) -> Function {
    trace(f, example).function
}

/// Traces `f` and runs the IR with the interpreter on `input`, returning
/// the output as `Native` values. Useful to check that a program gives the
/// same results natively and as IR.
///
/// # Panics
///
/// Panics if the interpreter fails, which indicates a bug.
pub fn interpret<I: Tree<Native>, O: Tree<Trace>>(
    f: impl FnOnce(I::On<Trace>) -> O,
    input: &I,
) -> O::On<Native> {
    let (traced, out) = trace_with_output(f, input);
    let args = leaves(input);
    let outs: Vec<HostArray> =
        ruxla_interp::eval(&traced.function, &args).unwrap_or_else(|e| panic!("{e}"));
    out.rebuild::<Native>(&mut outs.into_iter())
}