Skip to main content

pure_callback

Function pure_callback 

Source
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>,
Expand description

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.