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
//! `vmap`: batching programs.

use std::fmt;

use std::sync::Arc;

use ruxla_ir::{AVal, HostArray, Params};
use ruxla_pjrt::Buffer;

use crate::backend::{Native, Trace};
use crate::runtime::{self, Error};
use crate::trace::{self, TraceRef, trace_function};
use crate::transform::trace_with_output;
use crate::tree::{Tree, leaves};

/// Returns `f` batched over examples, like `jax.vmap` with every input and
/// output batched at dimension 0.
///
/// `f` takes and returns pytrees of [`Trace`] values for one example. It is
/// traced once, and the IR is batched by ruxla's `vmap` (the same
/// transformation that JAX's `vmap` of an exported program uses), so the
/// batched program has no loop. [`Vmap::call`] runs it with the interpreter
/// and [`Vmap::call_xla`] with XLA. To run a generic program natively for
/// many examples, call it in a loop (or use `ruxla_env::VecEnv`).
///
/// # Examples
///
/// ```
/// use ruxla_core::{F32, Trace, vmap};
///
/// let f = vmap(|(x, y): (F32<Trace>, F32<Trace>)| x * y + 1.0);
/// let out = f.call(&[(F32::new(2.0), F32::new(3.0)), (F32::new(4.0), F32::new(0.5))]);
/// assert_eq!(out.iter().map(|v| v.value()).collect::<Vec<_>>(), [7.0, 3.0]);
/// ```
pub fn vmap<F>(f: F) -> Vmap<F> {
    Vmap { f }
}

/// A batched function; see [`vmap`].
pub struct Vmap<F> {
    f: F,
}

impl<F> fmt::Debug for Vmap<F> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Vmap").finish_non_exhaustive()
    }
}

/// A batched function, its stacked arguments, and the structure of one
/// output.
struct Batched<O> {
    function: ruxla_ir::Function,
    args: Vec<HostArray>,
    out: O,
    size: usize,
}

/// Stacks arrays of the same type along a new leading dimension.
fn stack(xs: &[HostArray]) -> HostArray {
    let first = &xs[0];
    let mut bytes = Vec::with_capacity(first.to_bytes().len() * xs.len());
    for x in xs {
        assert_eq!(
            x.aval(),
            first.aval(),
            "vmap: the examples must have the same types"
        );
        bytes.extend(x.to_bytes());
    }
    let mut shape = vec![xs.len()];
    shape.extend_from_slice(first.shape());
    HostArray::from_bytes(&bytes, shape, first.dtype()).expect("consistent sizes")
}

/// Element `i` along the leading dimension.
fn unstack(x: &HostArray, i: usize) -> HostArray {
    let shape = x.shape()[1..].to_vec();
    let n: usize = shape.iter().product::<usize>() * x.dtype().size_in_bytes();
    HostArray::from_bytes(&x.to_bytes()[i * n..(i + 1) * n], shape, x.dtype())
        .expect("consistent sizes")
}

impl<F> Vmap<F> {
    fn batch<I, O>(&self, examples: &[I]) -> Batched<O>
    where
        I: Tree<Native>,
        O: Tree<Trace>,
        F: Fn(I::On<Trace>) -> O,
    {
        assert!(!examples.is_empty(), "vmap needs at least one example");
        let (traced, out) = trace_with_output(&self.f, &examples[0]);
        let per_example: Vec<Vec<HostArray>> = examples
            .iter()
            .map(|e| {
                assert_eq!(
                    e.def(),
                    traced.in_def,
                    "vmap: the examples must have the same structure"
                );
                leaves(e)
            })
            .collect();
        let args = (0..per_example[0].len())
            .map(|j| stack(&per_example.iter().map(|l| l[j].clone()).collect::<Vec<_>>()))
            .collect();
        let n = examples.len();
        let in_axes = vec![Some(0); traced.function.invars.len()];
        let out_axes = vec![Some(0); traced.function.outvars.len()];
        let function =
            ruxla_transforms::vmap_with_out_axes(&traced.function, &in_axes, &out_axes, n)
                .unwrap_or_else(|e| panic!("vmap: {e}"));
        Batched {
            function,
            args,
            out,
            size: n,
        }
    }

    fn unbatch<O: Tree<Trace>>(b: &Batched<O>, outs: &[HostArray]) -> Vec<O::On<Native>> {
        (0..b.size)
            .map(|i| {
                let leaves: Vec<HostArray> = outs.iter().map(|x| unstack(x, i)).collect();
                b.out.rebuild::<Native>(&mut leaves.into_iter())
            })
            .collect()
    }

    /// Runs the batched program on `examples` with the interpreter and
    /// returns one output per example.
    ///
    /// # Panics
    ///
    /// Panics if there are no examples, if they differ in structure or
    /// types, or if a primitive cannot be batched.
    pub fn call<I, O>(&self, examples: &[I]) -> Vec<O::On<Native>>
    where
        I: Tree<Native>,
        O: Tree<Trace>,
        F: Fn(I::On<Trace>) -> O,
    {
        let b = self.batch(examples);
        let outs = ruxla_interp::eval(&b.function, &b.args).unwrap_or_else(|e| panic!("{e}"));
        Self::unbatch(&b, &outs)
    }

    /// Runs the batched program on `examples` with XLA and returns one
    /// output per example.
    ///
    /// # Errors
    ///
    /// Returns an error if no PJRT plugin is configured, or if compiling or
    /// running fails.
    ///
    /// # Panics
    ///
    /// See [`Vmap::call`].
    pub fn call_xla<I, O>(&self, examples: &[I]) -> Result<Vec<O::On<Native>>, Error>
    where
        I: Tree<Native>,
        O: Tree<Trace>,
        F: Fn(I::On<Trace>) -> O,
    {
        let b = self.batch(examples);
        let platform = runtime::platform();
        let client = runtime::client(platform)?;
        let exe = runtime::compile(platform, &b.function)?;
        let buffers = b
            .args
            .iter()
            .map(|a| client.buffer_from_host_array(a))
            .collect::<Result<Vec<_>, _>>()?;
        let outs = exe.execute(&buffers.iter().collect::<Vec<_>>())?;
        let outs = outs
            .iter()
            .map(Buffer::to_host_array)
            .collect::<Result<Vec<HostArray>, _>>()?;
        Ok(Self::unbatch(&b, &outs))
    }

    /// Calls the batched function inside another trace on `examples`,
    /// pytrees of `Trace` values whose arrays are stacked along a new
    /// leading dimension (the number of examples). The batched body becomes
    /// a `jit` equation of the outer IR. Values that `f` captures from the
    /// outer trace are shared by all examples (not batched).
    ///
    /// The stacked values have the types of one example, so a stacked
    /// [`Scalar`](crate::Scalar) holds an array of rank 1: pass such values
    /// on (to another `vmap`, a loop's carry, or an output) without
    /// computing with them, and return arrays of rank 0 from `f` for values
    /// to compute with afterwards.
    ///
    /// # Examples
    ///
    /// ```
    /// use ruxla_core::{Array, F32, Trace, interpret, vmap};
    ///
    /// let f = |(xs, y): (Array<Trace, f32>, F32<Trace>)| {
    ///     vmap(|x: Array<Trace, f32>| x * y).call_traced(xs)
    /// };
    /// let out = interpret(f, &(Array::from_vec(vec![1.0f32, 2.0, 3.0], [3]), F32::new(2.0)));
    /// assert_eq!(out.to_vec(), [2.0, 4.0, 6.0]);
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the leaves of `examples` do not have the same leading
    /// dimension, or if a primitive cannot be batched.
    pub fn call_traced<I, O>(&self, examples: I) -> O
    where
        I: Tree<Trace>,
        O: Tree<Trace>,
        F: Fn(I) -> O,
    {
        let args: Vec<TraceRef> = leaves(&examples);
        let avals: Vec<AVal> = args.iter().map(|&r| trace::aval(r)).collect();
        let n = avals
            .first()
            .and_then(|a| a.shape.first().copied())
            .expect("vmap needs an input array with a leading dimension");
        let in_avals: Vec<AVal> = avals
            .iter()
            .map(|a| {
                assert_eq!(
                    a.shape.first(),
                    Some(&n),
                    "vmap: the inputs must have the same leading dimension"
                );
                AVal::new(a.shape[1..].to_vec(), a.dtype)
            })
            .collect();
        let mut out: Option<O> = None;
        let traced = trace_function(&in_avals, |refs| {
            let o = (self.f)(examples.unflatten_like(&mut refs.iter().copied()));
            let l = leaves(&o);
            out = Some(o);
            l
        });
        let ncap = traced.captured.len();
        let mut in_axes = vec![None; ncap];
        in_axes.extend(vec![Some(0); args.len()]);
        let out_axes = vec![Some(0); traced.function.outvars.len()];
        let body = ruxla_transforms::vmap_with_out_axes(&traced.function, &in_axes, &out_axes, n)
            .unwrap_or_else(|e| panic!("vmap: {e}"));
        let mut inputs = traced.captured;
        inputs.extend(args);
        let outs = trace::bind(
            ruxla_prims::JIT,
            &inputs,
            Params::Jit {
                name: String::from("vmap"),
                body: Arc::new(body),
            },
        );
        out.expect("the function was called")
            .unflatten_like(&mut outs.into_iter())
    }

    /// Returns the batched IR for `n` examples shaped like `example`.
    ///
    /// # Panics
    ///
    /// Panics if a primitive cannot be batched.
    pub fn make_ir<I, O>(&self, example: &I, n: usize) -> ruxla_ir::Function
    where
        I: Tree<Native>,
        O: Tree<Trace>,
        F: Fn(I::On<Trace>) -> O,
    {
        let (traced, _) = trace_with_output(&self.f, example);
        let in_avals: Vec<AVal> = traced.function.in_avals();
        let in_axes = vec![Some(0); in_avals.len()];
        let out_axes = vec![Some(0); traced.function.outvars.len()];
        ruxla_transforms::vmap_with_out_axes(&traced.function, &in_axes, &out_axes, n)
            .unwrap_or_else(|e| panic!("vmap: {e}"))
    }
}