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
//! `jit`: compiling programs with XLA.

use std::any::Any;
use std::collections::HashMap;
use std::fmt;
use std::sync::{Arc, Mutex, PoisonError};

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

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

/// Returns `f` compiled with XLA, like `jax.jit`.
///
/// `f` takes and returns pytrees of [`Trace`] values. The result is called
///
/// - with `Native` values ([`Jit::call`]): `f` is traced for the input types
///   (once per combination of types and structure), compiled with XLA
///   (cached), and run; inputs and outputs are copied to and from the
///   device;
/// - with values on the device ([`Jit::call_on_device`]), which stay there;
/// - with `Trace` values inside another trace ([`Jit::call_traced`]): the
///   traced body becomes a `jit` equation of the outer IR.
///
/// # Examples
///
/// ```no_run
/// use ruxla_core::{Array, F32, Trace, jit, jnp};
///
/// let f = jit(|(x, y): (Array<Trace, f32>, F32<Trace>)| jnp::sin(&(x * y)));
/// let out = f.call(&(Array::from_vec(vec![1.0f32, 2.0], [2]), F32::new(3.0)));
/// assert_eq!(out.shape().to_vec(), [2]);
/// ```
pub fn jit<F>(f: F) -> Jit<F> {
    Jit {
        f,
        name: String::from("jit"),
        cache: Mutex::new(HashMap::new()),
        skeletons: Mutex::new(HashMap::new()),
    }
}

/// A function compiled with XLA; see [`jit`].
pub struct Jit<F> {
    f: F,
    name: String,
    cache: Mutex<HashMap<(TreeDef, Vec<AVal>), Specialization>>,
    /// The structures of the results on the device, by the input's
    /// structure and types (`O::On<Native>` with zeros).
    skeletons: Mutex<HashMap<(TreeDef, Vec<AVal>), Specialization>>,
}

/// A [`Compiled`] of some output type, keyed by the input's structure and
/// types.
type Specialization = Arc<dyn Any + Send + Sync>;

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

/// A traced and compiled specialization of a [`Jit`].
struct Compiled<O> {
    function: Function,
    /// The output of tracing, whose structure (and static fields) the
    /// results take.
    out: O,
    platform: Platform,
}

impl<F> Jit<F> {
    /// Sets the name shown in the IR (the default is `jit`).
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = name.into();
        self
    }

    fn compiled<I, O>(&self, input: &I) -> Arc<Compiled<O>>
    where
        I: Tree<Native>,
        O: Tree<Trace> + Send + Sync + 'static,
        F: Fn(I::On<Trace>) -> O,
    {
        let avals: Vec<AVal> = leaves(input).iter().map(Native::leaf_aval).collect();
        let key = (input.def(), avals);
        let cached = self
            .cache
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .get(&key)
            .cloned();
        if let Some(c) = cached.and_then(|c| c.downcast::<Compiled<O>>().ok()) {
            return c;
        }
        let (traced, out) = trace_with_output(&self.f, input);
        let compiled = Arc::new(Compiled {
            function: traced.function,
            out,
            platform: runtime::platform(),
        });
        self.cache
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .insert(key, compiled.clone());
        compiled
    }

    /// Runs the function on `Native` values with XLA.
    ///
    /// # Panics
    ///
    /// Panics if the runtime fails (see [`Jit::try_call`]), or if `f` uses
    /// traced values of another trace.
    #[track_caller]
    pub fn call<I, O>(&self, input: &I) -> O::On<Native>
    where
        I: Tree<Native>,
        O: Tree<Trace> + Send + Sync + 'static,
        F: Fn(I::On<Trace>) -> O,
    {
        self.try_call(input).unwrap_or_else(|e| panic!("{e}"))
    }

    /// Runs the function on `Native` values with XLA.
    ///
    /// # Errors
    ///
    /// Returns an error if no PJRT plugin is configured (see
    /// [`runtime`](crate::runtime)), or if compiling or running fails.
    pub fn try_call<I, O>(&self, input: &I) -> Result<O::On<Native>, Error>
    where
        I: Tree<Native>,
        O: Tree<Trace> + Send + Sync + 'static,
        F: Fn(I::On<Trace>) -> O,
    {
        let c = self.compiled::<I, O>(input);
        let client = runtime::client(c.platform)?;
        let buffers = leaves(input)
            .iter()
            .map(|a| client.buffer_from_host_array(a))
            .collect::<Result<Vec<_>, _>>()?;
        let outs = execute(&c, &buffers.iter().collect::<Vec<_>>())?;
        let outs = outs
            .iter()
            .map(Buffer::to_host_array)
            .collect::<Result<Vec<HostArray>, _>>()?;
        Ok(c.out.rebuild::<Native>(&mut outs.into_iter()))
    }

    /// Runs the function with XLA on values on the device, and returns the
    /// results on the device.
    ///
    /// # Panics
    ///
    /// Panics if the runtime fails, or if the values are on another
    /// platform.
    #[track_caller]
    pub fn call_on_device<I, O>(&self, input: &OnDevice<I>) -> OnDevice<O::On<Native>>
    where
        I: Tree<Native>,
        O: Tree<Trace> + Send + Sync + 'static,
        O::On<Native>: Send + Sync + 'static,
        F: Fn(I::On<Trace>) -> O,
    {
        let c = self.compiled::<I, O>(&input.skeleton);
        assert_eq!(
            c.platform, input.platform,
            "the values are on another platform"
        );
        let args: Vec<&Buffer> = input.buffers.iter().map(Arc::as_ref).collect();
        let exe = runtime::compile(c.platform, &c.function).unwrap_or_else(|e| panic!("{e}"));
        // The device runs executions in order, so the results are returned
        // without waiting; copying them to the host waits for them.
        let (outs, _done) = exe
            .execute_with(&args, &ExecuteOptions::default())
            .unwrap_or_else(|e| panic!("{e}"));
        self.on_device(&c, &input.skeleton, outs)
    }

    /// [`Jit::call_on_device`] taking the input, whose buffers the program
    /// may reuse for the results (donation, as with JAX's
    /// `donate_argnums`), which saves memory and copies in loops such as
    /// `state = step.call_on_device_donating(state)`. Leaves whose buffers
    /// are shared with another `OnDevice` (a clone) are not donated.
    ///
    /// # Panics
    ///
    /// Panics if the runtime fails, or if the values are on another
    /// platform.
    #[track_caller]
    pub fn call_on_device_donating<I, O>(&self, input: OnDevice<I>) -> OnDevice<O::On<Native>>
    where
        I: Tree<Native>,
        O: Tree<Trace> + Send + Sync + 'static,
        O::On<Native>: Send + Sync + 'static,
        F: Fn(I::On<Trace>) -> O,
    {
        let c = self.compiled::<I, O>(&input.skeleton);
        assert_eq!(
            c.platform, input.platform,
            "the values are on another platform"
        );
        let donated = vec![true; input.buffers.len()];
        let exe = runtime::compile_donating(c.platform, &c.function, &donated)
            .unwrap_or_else(|e| panic!("{e}"));
        let options = ExecuteOptions {
            non_donatable: input
                .buffers
                .iter()
                .enumerate()
                .filter(|(_, b)| Arc::strong_count(b) > 1)
                .map(|(i, _)| i as i64)
                .collect(),
        };
        let args: Vec<&Buffer> = input.buffers.iter().map(Arc::as_ref).collect();
        let (outs, _done) = exe
            .execute_with(&args, &options)
            .unwrap_or_else(|e| panic!("{e}"));
        self.on_device(&c, &input.skeleton, outs)
    }

    /// Wraps the results of an execution on the device.
    fn on_device<I, O>(
        &self,
        c: &Compiled<O>,
        input: &I,
        outs: Vec<Buffer>,
    ) -> OnDevice<O::On<Native>>
    where
        I: Tree<Native>,
        O: Tree<Trace> + Send + Sync + 'static,
        O::On<Native>: Send + Sync + 'static,
    {
        let avals: Vec<AVal> = leaves(input).iter().map(Native::leaf_aval).collect();
        let key = (input.def(), avals);
        let cached = self
            .skeletons
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .get(&key)
            .cloned()
            .and_then(|s| s.downcast::<O::On<Native>>().ok());
        let skeleton = match cached {
            Some(s) => (*s).clone(),
            None => {
                // Zeros of the output types, which give `to_native` the
                // structure and static fields.
                let zeros: Vec<HostArray> = c
                    .function
                    .out_avals()
                    .iter()
                    .map(|a| HostArray::zeros(a.shape.clone(), a.dtype))
                    .collect();
                let s = c.out.rebuild::<Native>(&mut zeros.into_iter());
                self.skeletons
                    .lock()
                    .unwrap_or_else(PoisonError::into_inner)
                    .insert(key, Arc::new(s.clone()));
                s
            }
        };
        OnDevice {
            skeleton,
            buffers: outs.into_iter().map(Arc::new).collect(),
            platform: c.platform,
        }
    }

    /// Calls the function on `Trace` values inside another trace, which
    /// adds a `jit` equation with the traced body to the outer IR.
    pub fn call_traced<I, O>(&self, input: I) -> O
    where
        I: Tree<Trace>,
        O: Tree<Trace>,
        F: Fn(I) -> O,
    {
        let args = leaves(&input);
        let in_avals: Vec<AVal> = args.iter().map(|&r| trace::aval(r)).collect();
        let mut out: Option<O> = None;
        let traced = trace_function(&in_avals, |refs| {
            let o = (self.f)(input.unflatten_like(&mut refs.iter().copied()));
            let l = leaves(&o);
            out = Some(o);
            l
        });
        let mut inputs: Vec<TraceRef> = traced.captured;
        inputs.extend(args);
        let outs = trace::bind(
            ruxla_prims::JIT,
            &inputs,
            Params::Jit {
                name: self.name.clone(),
                body: Arc::new(traced.function),
            },
        );
        out.expect("the function was called")
            .unflatten_like(&mut outs.into_iter())
    }
}

fn execute<O>(c: &Compiled<O>, args: &[&Buffer]) -> Result<Vec<Buffer>, Error> {
    let exe = runtime::compile(c.platform, &c.function)?;
    Ok(exe.execute(args)?)
}

/// A pytree whose arrays are on the device of the runtime's platform, made
/// by [`device_put`] or returned by [`Jit::call_on_device`].
///
/// There are no operations on it other than passing it to jitted functions
/// and copying it back with [`OnDevice::to_native`].
pub struct OnDevice<T> {
    /// A value of the same structure and static fields (its arrays are not
    /// the device values).
    skeleton: T,
    buffers: Vec<Arc<Buffer>>,
    platform: Platform,
}

impl<T: Clone> Clone for OnDevice<T> {
    fn clone(&self) -> Self {
        Self {
            skeleton: self.skeleton.clone(),
            buffers: self.buffers.clone(),
            platform: self.platform,
        }
    }
}

impl<T> fmt::Debug for OnDevice<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("OnDevice")
            .field("platform", &self.platform)
            .field("leaves", &self.buffers.len())
            .finish_non_exhaustive()
    }
}

impl<T: Tree<Native>> OnDevice<T> {
    /// Copies the values to the host.
    ///
    /// # Panics
    ///
    /// Panics if the transfer fails.
    pub fn to_native(&self) -> T {
        let host: Vec<HostArray> = self
            .buffers
            .iter()
            .map(|b| b.to_host_array().unwrap_or_else(|e| panic!("{e}")))
            .collect();
        self.skeleton.unflatten_like(&mut host.into_iter())
    }
}

/// Copies a pytree of `Native` values to the device of the runtime's
/// platform.
///
/// # Panics
///
/// Panics if no PJRT plugin is configured or the transfer fails.
pub fn device_put<T: Tree<Native>>(x: &T) -> OnDevice<T> {
    let platform = runtime::platform();
    let client = runtime::client(platform).unwrap_or_else(|e| panic!("{e}"));
    let buffers = leaves(x)
        .iter()
        .map(|a| {
            client
                .buffer_from_host_array(a)
                .map(Arc::new)
                .unwrap_or_else(|e| panic!("{e}"))
        })
        .collect();
    OnDevice {
        skeleton: x.clone(),
        buffers,
        platform,
    }
}