ruxla_core/callback.rs
1//! Calling native code from programs that may be traced.
2
3use ruxla_ir::callback::HostCallback;
4
5use crate::backend::{Backend, Native};
6use crate::tree::{Tree, leaves};
7
8/// Calls the native function `f` on `input` from code of any backend, as
9/// JAX's `pure_callback`: natively, `f` runs directly; in a trace, the call
10/// is a `host_callback` equation, which the interpreter and ruxla's XLA
11/// runtime (CPU, and CUDA around copies to the host) run by calling `f` on
12/// the host. `like` gives the structure and types of the results (its
13/// values are not used). Code that cannot be written for every backend
14/// (external libraries, arbitrary data structures) can thus
15/// run inside `jit`, `vmap` (a loop over the examples), and the programs of
16/// environments.
17///
18/// `f` must be pure: it may run any number of times, or not at all if its
19/// results are unused. The call is not differentiable, and programs with it
20/// cannot be serialized (`.ruxlapkg`), embedded in JAX, or compiled to Rust.
21///
22/// # Examples
23///
24/// ```
25/// use ruxla_core::{Array, Native, Trace, interpret, pure_callback};
26///
27/// // A native function (here, a sort with the standard library).
28/// fn sorted(x: Array<Native, f32>) -> Array<Native, f32> {
29/// let mut v = x.to_vec();
30/// v.sort_by(f32::total_cmp);
31/// Array::from_vec(v, [3])
32/// }
33/// let like = Array::<Native, f32>::from_vec(vec![0.0; 3], [3]);
34/// let x = Array::<Native, f32>::from_vec(vec![3.0, 1.0, 2.0], [3]);
35/// // Natively, and traced and run by the interpreter.
36/// assert_eq!(pure_callback("sorted", sorted, &like, &x).to_vec(), [1.0, 2.0, 3.0]);
37/// let out = interpret(
38/// |x: Array<Trace, f32>| pure_callback("sorted", sorted, &like, &x) * 2.0,
39/// &x,
40/// );
41/// assert_eq!(out.to_vec(), [2.0, 4.0, 6.0]);
42/// ```
43///
44/// # Panics
45///
46/// Panics natively if `f` returns other types than `like`'s; in a program,
47/// that is an error when it runs.
48#[track_caller]
49pub fn pure_callback<B, I, O>(
50 name: &str,
51 f: impl Fn(I::On<Native>) -> O + Send + Sync + 'static,
52 like: &O,
53 input: &I,
54) -> O::On<B>
55where
56 B: Backend,
57 I: Tree<B> + Send + Sync + 'static,
58 O: Tree<Native>,
59{
60 let outputs: Vec<_> = leaves(like).iter().map(Native::leaf_aval).collect();
61 let template = input.clone();
62 let callback = HostCallback::new(name, move |args| {
63 let x = template.rebuild::<Native>(&mut args.iter().cloned());
64 Ok(leaves::<Native, O>(&f(x)))
65 });
66 let results = B::host_callback(&callback, &leaves(input), &outputs);
67 like.rebuild::<B>(&mut results.into_iter())
68}