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
//! Calling native code from programs that may be traced.

use ruxla_ir::callback::HostCallback;

use crate::backend::{Backend, Native};
use crate::tree::{Tree, leaves};

/// Calls the native function `f` on `input` from code of any backend, as
/// JAX's `pure_callback`: natively, `f` runs directly; in a trace, the call
/// is a `host_callback` equation, which the interpreter and ruxla's XLA
/// runtime (CPU, and CUDA around copies to the host) run by calling `f` on
/// the host. `like` gives the structure and types of the results (its
/// values are not used). Code that cannot be written for every backend
/// (external libraries, arbitrary data structures) can thus
/// run inside `jit`, `vmap` (a loop over the examples), and the programs of
/// environments.
///
/// `f` must be pure: it may run any number of times, or not at all if its
/// results are unused. The call is not differentiable, and programs with it
/// cannot be serialized (`.ruxlapkg`), embedded in JAX, or compiled to Rust.
///
/// # Examples
///
/// ```
/// use ruxla_core::{Array, Native, Trace, interpret, pure_callback};
///
/// // A native function (here, a sort with the standard library).
/// fn sorted(x: Array<Native, f32>) -> Array<Native, f32> {
///     let mut v = x.to_vec();
///     v.sort_by(f32::total_cmp);
///     Array::from_vec(v, [3])
/// }
/// let like = Array::<Native, f32>::from_vec(vec![0.0; 3], [3]);
/// let x = Array::<Native, f32>::from_vec(vec![3.0, 1.0, 2.0], [3]);
/// // Natively, and traced and run by the interpreter.
/// assert_eq!(pure_callback("sorted", sorted, &like, &x).to_vec(), [1.0, 2.0, 3.0]);
/// let out = interpret(
///     |x: Array<Trace, f32>| pure_callback("sorted", sorted, &like, &x) * 2.0,
///     &x,
/// );
/// assert_eq!(out.to_vec(), [2.0, 4.0, 6.0]);
/// ```
///
/// # Panics
///
/// Panics natively if `f` returns other types than `like`'s; in a program,
/// that is an error when it runs.
#[track_caller]
pub fn pure_callback<B, I, O>(
    name: &str,
    f: impl Fn(I::On<Native>) -> O + Send + Sync + 'static,
    like: &O,
    input: &I,
) -> O::On<B>
where
    B: Backend,
    I: Tree<B> + Send + Sync + 'static,
    O: Tree<Native>,
{
    let outputs: Vec<_> = leaves(like).iter().map(Native::leaf_aval).collect();
    let template = input.clone();
    let callback = HostCallback::new(name, move |args| {
        let x = template.rebuild::<Native>(&mut args.iter().cloned());
        Ok(leaves::<Native, O>(&f(x)))
    });
    let results = B::host_callback(&callback, &leaves(input), &outputs);
    like.rebuild::<B>(&mut results.into_iter())
}