Skip to main content

ruxla_ir/
callback.rs

1//! Host callbacks: Rust functions on host arrays that programs call
2//! (`host_callback`, as JAX's `pure_callback`), so that native code that
3//! cannot be written generically runs inside traced programs.
4
5use std::collections::HashMap;
6use std::fmt;
7use std::sync::{Arc, Mutex, OnceLock, PoisonError};
8
9use crate::host::HostArray;
10
11/// The function of a host callback: the arguments to the results, or an
12/// error message.
13pub type HostFn = dyn Fn(&[HostArray]) -> Result<Vec<HostArray>, String> + Send + Sync;
14
15/// A Rust function called on host arrays by a program (`host_callback`).
16///
17/// Compiled programs refer to it by an id ([`HostCallback::id`]), under
18/// which it stays registered for the life of the process.
19///
20/// # Examples
21///
22/// ```
23/// use ruxla_ir::HostArray;
24/// use ruxla_ir::callback::HostCallback;
25///
26/// let double = HostCallback::new("double", |args: &[HostArray]| {
27///     let x = args[0].to_vec::<f32>().map_err(|e| e.to_string())?;
28///     let y: Vec<f32> = x.iter().map(|v| 2.0 * v).collect();
29///     Ok(vec![HostArray::from_vec(y, args[0].shape().clone())])
30/// });
31/// let out = double.call(&[HostArray::from_vec(vec![1.0f32, 2.0], [2])]).unwrap();
32/// assert_eq!(out[0].to_vec::<f32>().unwrap(), [2.0, 4.0]);
33/// ```
34#[derive(Clone)]
35pub struct HostCallback {
36    inner: Arc<Inner>,
37}
38
39struct Inner {
40    name: String,
41    f: Box<HostFn>,
42    id: OnceLock<u64>,
43}
44
45impl HostCallback {
46    /// A callback named `name` (for the printed IR and error messages).
47    pub fn new(
48        name: impl Into<String>,
49        f: impl Fn(&[HostArray]) -> Result<Vec<HostArray>, String> + Send + Sync + 'static,
50    ) -> Self {
51        Self {
52            inner: Arc::new(Inner {
53                name: name.into(),
54                f: Box::new(f),
55                id: OnceLock::new(),
56            }),
57        }
58    }
59
60    /// The name.
61    pub fn name(&self) -> &str {
62        &self.inner.name
63    }
64
65    /// Calls the function.
66    ///
67    /// # Errors
68    ///
69    /// Returns the function's error message.
70    pub fn call(&self, args: &[HostArray]) -> Result<Vec<HostArray>, String> {
71        (self.inner.f)(args)
72    }
73
74    /// The id under which compiled programs find the callback, registering
75    /// it (for the life of the process) the first time.
76    pub fn id(&self) -> u64 {
77        *self.inner.id.get_or_init(|| {
78            let mut r = registry().lock().unwrap_or_else(PoisonError::into_inner);
79            let id = r.len() as u64 + 1;
80            r.insert(id, self.clone());
81            id
82        })
83    }
84
85    /// The callback registered under `id` ([`HostCallback::id`]).
86    pub fn lookup(id: u64) -> Option<Self> {
87        registry()
88            .lock()
89            .unwrap_or_else(PoisonError::into_inner)
90            .get(&id)
91            .cloned()
92    }
93}
94
95fn registry() -> &'static Mutex<HashMap<u64, HostCallback>> {
96    static REGISTRY: OnceLock<Mutex<HashMap<u64, HostCallback>>> = OnceLock::new();
97    REGISTRY.get_or_init(Default::default)
98}
99
100impl PartialEq for HostCallback {
101    fn eq(&self, other: &Self) -> bool {
102        Arc::ptr_eq(&self.inner, &other.inner)
103    }
104}
105
106impl fmt::Debug for HostCallback {
107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108        f.debug_struct("HostCallback")
109            .field("name", &self.inner.name)
110            .finish_non_exhaustive()
111    }
112}