Skip to main content

ruxla_prims/
host_callback.rs

1//! `host_callback`: a Rust function on host arrays called by a program, as
2//! JAX's `pure_callback`.
3
4use std::sync::Arc;
5
6use ruxla_ir::batching::{BatchCx, Batched};
7use ruxla_ir::lowering::{HloValue, LowerCx, Target};
8use ruxla_ir::{AVal, Atom, Error, EvalCx, HostArray, Params, Prim, Primitive, Result};
9
10use crate::batching::bdim_at_front;
11use crate::linalg_lower::{FfiCall, ffi_call};
12use crate::util::wrong_params;
13
14/// `host_callback`.
15#[derive(Debug)]
16pub(crate) struct HostCallbackPrim;
17
18/// Calls a Rust function on host arrays ([`Params::HostCallback`]): the
19/// interpreter calls it directly, XLA through the FFI handler
20/// `ruxla_host_callback` of `ruxla-pjrt` (on CUDA, around copies to the
21/// host), which finds it by its id. The function must be pure (it may run
22/// any number of times). Not differentiable; batched by a loop over the
23/// examples (`scan`, as `pure_callback` with `vmap_method="sequential"`).
24/// Programs with host callbacks cannot be serialized, embedded in JAX, or
25/// compiled to Rust.
26pub static HOST_CALLBACK: Prim = Prim::new(&HostCallbackPrim);
27
28fn outputs_of<'a>(prim: &'static str, params: &'a Params) -> Result<&'a [AVal]> {
29    match params {
30        Params::HostCallback { outputs, .. } => Ok(outputs),
31        _ => Err(wrong_params(prim)),
32    }
33}
34
35impl Primitive for HostCallbackPrim {
36    fn name(&self) -> &'static str {
37        "host_callback"
38    }
39
40    fn abstract_eval(&self, _: &[AVal], params: &Params) -> Result<Vec<AVal>> {
41        Ok(outputs_of(self.name(), params)?.to_vec())
42    }
43
44    fn eval(
45        &self,
46        _: &dyn EvalCx,
47        inputs: &[HostArray],
48        params: &Params,
49    ) -> Result<Vec<HostArray>> {
50        let Params::HostCallback { callback, outputs } = params else {
51            return Err(wrong_params(self.name()));
52        };
53        let results = callback.call(inputs).map_err(|m| {
54            Error::unsupported(self.name(), format!("`{}` failed: {m}", callback.name()))
55        })?;
56        let got: Vec<AVal> = results.iter().map(HostArray::aval).collect();
57        if &got != outputs {
58            return Err(Error::type_error(
59                self.name(),
60                format!(
61                    "`{}` returned {got:?}, expected {outputs:?}",
62                    callback.name()
63                ),
64            ));
65        }
66        Ok(results)
67    }
68
69    fn lower(
70        &self,
71        cx: &mut dyn LowerCx,
72        inputs: &[HloValue],
73        params: &Params,
74        outputs: &[AVal],
75    ) -> Result<Vec<HloValue>> {
76        let Params::HostCallback { callback, .. } = params else {
77            return Err(wrong_params(self.name()));
78        };
79        if cx.target() != Target::Pjrt {
80            return Err(Error::unsupported(
81                self.name(),
82                format!(
83                    "`{}` is a Rust function, which only ruxla's XLA runtime calls",
84                    callback.name()
85                ),
86            ));
87        }
88        let config = format!("id = {} : i64", callback.id());
89        Ok(ffi_call(
90            cx,
91            &FfiCall {
92                target: "ruxla_host_callback",
93                operands: inputs,
94                results: outputs,
95                config: &config,
96                column_major: false,
97                aliases: &[],
98                num_non_batch_dims: None,
99            },
100        ))
101    }
102
103    /// A loop over the examples (`scan`): the function sees one example at
104    /// a time.
105    fn batch(
106        &'static self,
107        cx: &mut dyn BatchCx,
108        inputs: &[Batched],
109        params: &Params,
110    ) -> Result<Vec<Batched>> {
111        let outputs = outputs_of(self.name(), params)?.to_vec();
112        let n = cx.axis_size();
113        let mut consts = Vec::new();
114        let mut xs = Vec::new();
115        for x in inputs {
116            if x.bdim.is_some() {
117                xs.push(bdim_at_front(cx, x)?);
118            } else {
119                consts.push(x.atom.clone());
120            }
121        }
122        let batched: Vec<bool> = inputs.iter().map(|x| x.bdim.is_some()).collect();
123        // The types of one example of each input, constants first.
124        let example = |x: &Batched| {
125            let aval = x.atom.aval();
126            match x.bdim {
127                Some(d) => {
128                    let mut dims = aval.shape.dims().to_vec();
129                    dims.remove(d);
130                    AVal::new(dims, aval.dtype)
131                }
132                None => aval,
133            }
134        };
135        let body_avals: Vec<AVal> = inputs
136            .iter()
137            .filter(|x| x.bdim.is_none())
138            .chain(inputs.iter().filter(|x| x.bdim.is_some()))
139            .map(example)
140            .collect();
141        let num_consts = consts.len();
142        let p = params.clone();
143        let body = cx.build_function(&body_avals, &mut |cx, args| {
144            let (c, x) = args.split_at(num_consts);
145            let (mut c, mut x) = (c.iter(), x.iter());
146            let ordered: Vec<Atom> = batched
147                .iter()
148                .map(|&b| {
149                    if b { x.next() } else { c.next() }
150                        .expect("one argument per input")
151                        .clone()
152                })
153                .collect();
154            cx.bind(HOST_CALLBACK, &ordered, p.clone())
155        })?;
156        let mut scan_inputs = consts;
157        scan_inputs.extend(xs);
158        let outs = cx.bind(
159            crate::SCAN,
160            &scan_inputs,
161            Params::Scan {
162                body: Arc::new(body),
163                length: n,
164                reverse: false,
165                num_consts,
166                num_carry: 0,
167            },
168        )?;
169        debug_assert_eq!(outs.len(), outputs.len());
170        Ok(outs.into_iter().map(|a| Batched::mapped(a, 0)).collect())
171    }
172}