Skip to main content

ruxla_prims/
extern_call.rs

1//! `extern_call`: calling a StableHLO module written by another program.
2
3use std::sync::Arc;
4
5use ruxla_ir::batching::{BatchCx, Batched};
6use ruxla_ir::lowering::{HloValue, LowerCx};
7use ruxla_ir::{AVal, Atom, Error, EvalCx, HostArray, Params, Prim, Primitive, Result};
8
9use crate::batching::bdim_at_front;
10use crate::util::wrong_params;
11
12/// `extern_call`.
13#[derive(Debug)]
14pub(crate) struct ExternCall;
15
16/// Calls the public `main` of a StableHLO module written by another
17/// program, such as a JAX model exported with `jax.export`
18/// ([`Params::Extern`]). XLA links the module with the caller and compiles
19/// them together; the interpreter and the native backend cannot run it.
20pub static EXTERN_CALL: Prim = Prim::new(&ExternCall);
21
22impl Primitive for ExternCall {
23    fn name(&self) -> &'static str {
24        "extern_call"
25    }
26
27    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
28        let Params::Extern {
29            name,
30            inputs: expected,
31            outputs,
32            ..
33        } = params
34        else {
35            return Err(wrong_params(self.name()));
36        };
37        if inputs != expected.as_slice() {
38            return Err(Error::type_error(
39                self.name(),
40                format!("`{name}` takes {expected:?}, got {inputs:?}"),
41            ));
42        }
43        Ok(outputs.clone())
44    }
45
46    fn eval(&self, _: &dyn EvalCx, _: &[HostArray], params: &Params) -> Result<Vec<HostArray>> {
47        let name = match params {
48            Params::Extern { name, .. } => name.as_str(),
49            _ => "?",
50        };
51        Err(Error::unsupported(
52            self.name(),
53            format!("`{name}` is a StableHLO module, which only XLA runs (use jit)"),
54        ))
55    }
56
57    fn lower(
58        &self,
59        cx: &mut dyn LowerCx,
60        inputs: &[HloValue],
61        params: &Params,
62        outputs: &[AVal],
63    ) -> Result<Vec<HloValue>> {
64        let Params::Extern { name, module, .. } = params else {
65            return Err(wrong_params(self.name()));
66        };
67        let symbol = cx.import(module, name)?;
68        Ok(cx.op("func.call", inputs, &format!("callee = @{symbol}"), outputs))
69    }
70
71    /// The module is opaque, so the batched call is a loop over the
72    /// examples (`scan`), as `jax.lax.map` would do.
73    fn batch(
74        &'static self,
75        cx: &mut dyn BatchCx,
76        inputs: &[Batched],
77        params: &Params,
78    ) -> Result<Vec<Batched>> {
79        let Params::Extern {
80            inputs: in_avals,
81            outputs,
82            ..
83        } = params
84        else {
85            return Err(wrong_params(self.name()));
86        };
87        let n = cx.axis_size();
88        // Unbatched inputs are the constants of the scan, batched ones (with
89        // the batch dimension first) the scanned operands.
90        let mut consts = Vec::new();
91        let mut xs = Vec::new();
92        for x in inputs {
93            if x.bdim.is_some() {
94                xs.push(bdim_at_front(cx, x)?);
95            } else {
96                consts.push(x.atom.clone());
97            }
98        }
99        let batched: Vec<bool> = inputs.iter().map(|x| x.bdim.is_some()).collect();
100        let body_avals: Vec<AVal> = in_avals
101            .iter()
102            .zip(&batched)
103            .filter(|(_, b)| !**b)
104            .chain(in_avals.iter().zip(&batched).filter(|(_, b)| **b))
105            .map(|(a, _)| a.clone())
106            .collect();
107        let num_consts = consts.len();
108        let p = params.clone();
109        let body = cx.build_function(&body_avals, &mut |cx, args| {
110            // Put the arguments back in the order of the module's inputs.
111            let (c, x) = args.split_at(num_consts);
112            let (mut c, mut x) = (c.iter(), x.iter());
113            let ordered: Vec<Atom> = batched
114                .iter()
115                .map(|&b| {
116                    if b { x.next() } else { c.next() }
117                        .expect("one argument per input")
118                        .clone()
119                })
120                .collect();
121            cx.bind(EXTERN_CALL, &ordered, p.clone())
122        })?;
123        let mut scan_inputs = consts;
124        scan_inputs.extend(xs);
125        let outs = cx.bind(
126            crate::SCAN,
127            &scan_inputs,
128            Params::Scan {
129                body: Arc::new(body),
130                length: n,
131                reverse: false,
132                num_consts,
133                num_carry: 0,
134            },
135        )?;
136        debug_assert_eq!(outs.len(), outputs.len());
137        Ok(outs.into_iter().map(|a| Batched::mapped(a, 0)).collect())
138    }
139}