1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
//! Calling native code from programs that may be traced.
use HostCallback;
use crate;
use crate;
/// 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.