Skip to main content

ruxla_core/
extern_fn.rs

1//! Calling StableHLO modules written by other programs, such as JAX models
2//! exported with `jax.export`.
3
4use std::fmt;
5use std::sync::Arc;
6
7use ruxla_ir::{AVal, DType, Params};
8
9use crate::backend::{Backend as _, Native, Trace};
10use crate::trace::{self, TraceRef};
11use crate::tree::{Tree, leaves};
12
13/// An error from reading a module for [`ExternFn`].
14#[derive(Debug, thiserror::Error)]
15#[non_exhaustive]
16pub enum ExternError {
17    /// The module has no public `main` function.
18    #[error("the module has no public `main` function")]
19    NoMain,
20    /// The signature of `main` could not be read.
21    #[error("cannot read the signature of `main`: {0}")]
22    Signature(String),
23}
24
25/// A StableHLO module written by another program, called like a function
26/// from traced programs: XLA links it with the caller and compiles them
27/// together (`extern_call`). The interpreter and the native backend cannot
28/// run it, so programs that call it run with [`jit`](crate::jit).
29///
30/// # Examples
31///
32/// ```
33/// use ruxla_core::{Array, ExternFn, Native, Trace, make_ir};
34///
35/// let module = r#"
36/// module @jit_f {
37///   func.func public @main(%x: tensor<2xf32>) -> (tensor<2xf32>) {
38///     %0 = stablehlo.multiply %x, %x : tensor<2xf32>
39///     return %0 : tensor<2xf32>
40///   }
41/// }
42/// "#;
43/// let f = ExternFn::from_mlir("square", module).unwrap();
44/// let like = Array::<Native, f32>::from_vec(vec![0.0; 2], [2]);
45/// let ir = make_ir(|x: Array<Trace, f32>| f.call(&x, &like), &like);
46/// assert!(ir.to_string().contains("extern_call[name=square"));
47/// ```
48#[derive(Clone)]
49pub struct ExternFn {
50    name: String,
51    module: Arc<str>,
52    inputs: Vec<AVal>,
53    outputs: Vec<AVal>,
54    /// The VJP of the function, if given ([`ExternFn::with_vjp`]).
55    vjp: Option<Arc<ExternFn>>,
56}
57
58impl fmt::Debug for ExternFn {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        f.debug_struct("ExternFn")
61            .field("name", &self.name)
62            .field("inputs", &self.inputs)
63            .field("outputs", &self.outputs)
64            .finish_non_exhaustive()
65    }
66}
67
68impl ExternFn {
69    /// Reads a module in the MLIR text format (such as
70    /// `jax.export.Exported.mlir_module()`), whose public `main` is the
71    /// function; `name` names it in the IR and in the linked module.
72    ///
73    /// # Errors
74    ///
75    /// Returns an error if the module has no public `main` or its signature
76    /// has types that ruxla does not have.
77    pub fn from_mlir(
78        name: impl Into<String>,
79        module: impl Into<String>,
80    ) -> Result<Self, ExternError> {
81        let module: String = module.into();
82        let (inputs, outputs) = signature(&module)?;
83        Ok(Self {
84            name: name.into(),
85            module: module.into(),
86            inputs,
87            outputs,
88            vjp: None,
89        })
90    }
91
92    /// Makes the function differentiable in reverse mode with its VJP: a
93    /// module that takes the inputs and a cotangent for each output and
94    /// returns a cotangent for each input, such as the one that
95    /// `jax.export`'s `Exported.vjp()` writes. The call is then a
96    /// `custom_vjp_call` whose backward function calls the VJP.
97    ///
98    /// # Errors
99    ///
100    /// Returns an error if the VJP does not have the signature that the
101    /// function requires.
102    pub fn with_vjp(mut self, vjp: ExternFn) -> Result<Self, ExternError> {
103        let mut expected = self.inputs.clone();
104        expected.extend(self.outputs.iter().cloned());
105        if vjp.inputs != expected || vjp.outputs != self.inputs {
106            return Err(ExternError::Signature(format!(
107                "the VJP of `{}` must take {expected:?} and return {:?}, but takes {:?} and returns {:?}",
108                self.name, self.inputs, vjp.inputs, vjp.outputs
109            )));
110        }
111        self.vjp = Some(Arc::new(vjp));
112        Ok(self)
113    }
114
115    /// The types of the inputs of `main`.
116    pub fn inputs(&self) -> &[AVal] {
117        &self.inputs
118    }
119
120    /// The types of the outputs of `main`.
121    pub fn outputs(&self) -> &[AVal] {
122        &self.outputs
123    }
124
125    /// Calls the module on the leaves of `input` and returns its outputs in
126    /// the structure of `like` (a pytree of native values of the output
127    /// types, whose values are not used).
128    ///
129    /// # Panics
130    ///
131    /// Panics if the leaves of `input` or `like` do not have the types of the
132    /// module's inputs or outputs.
133    #[track_caller]
134    pub fn call<I: Tree<Trace>, O: Tree<Native>>(&self, input: &I, like: &O) -> O::On<Trace> {
135        let args: Vec<TraceRef> = leaves(input);
136        let out_avals: Vec<AVal> = leaves(like).iter().map(Native::leaf_aval).collect();
137        assert_eq!(
138            out_avals, self.outputs,
139            "`{}` returns {:?}, but the outputs are expected to be {out_avals:?}",
140            self.name, self.outputs
141        );
142        let Some(vjp) = &self.vjp else {
143            return like.rebuild::<Trace>(&mut self.bind(&args).into_iter());
144        };
145        // `custom_vjp` with the inputs as residuals; the backward function
146        // calls the VJP on the inputs and the cotangents.
147        let f = |x: I| like.rebuild::<Trace>(&mut self.bind(&leaves(&x)).into_iter());
148        let fwd = |x: I| (f(x.clone()), x);
149        let bwd = |x: I, ct: O::On<Trace>| {
150            let mut vjp_args = leaves(&x);
151            vjp_args.extend(leaves(&ct));
152            x.unflatten_like(&mut vjp.bind(&vjp_args).into_iter())
153        };
154        crate::lax::custom_vjp(f, fwd, bwd, input.clone())
155    }
156
157    /// Adds an `extern_call` of the module to the current trace.
158    fn bind(&self, args: &[TraceRef]) -> Vec<TraceRef> {
159        trace::bind(
160            ruxla_prims::EXTERN_CALL,
161            args,
162            Params::Extern {
163                name: self.name.clone(),
164                module: self.module.clone(),
165                inputs: self.inputs.clone(),
166                outputs: self.outputs.clone(),
167            },
168        )
169    }
170}
171
172/// Reads the input and output types of the public `main` of a module.
173fn signature(module: &str) -> Result<(Vec<AVal>, Vec<AVal>), ExternError> {
174    let start = ["func.func public @main(", "func.func @main("]
175        .iter()
176        .find_map(|p| module.find(p).map(|i| i + p.len()))
177        .ok_or(ExternError::NoMain)?;
178    let rest = &module[start..];
179    let args_end = closing_paren(rest)
180        .ok_or_else(|| ExternError::Signature(String::from("unbalanced parentheses")))?;
181    let inputs = tensor_types(&rest[..args_end])?;
182    let after = rest[args_end + 1..].trim_start();
183    let after = after
184        .strip_prefix("->")
185        .ok_or_else(|| ExternError::Signature(String::from("no results")))?
186        .trim_start();
187    let results = if let Some(r) = after.strip_prefix('(') {
188        let end = closing_paren(r)
189            .ok_or_else(|| ExternError::Signature(String::from("unbalanced parentheses")))?;
190        &r[..end]
191    } else {
192        // A single result type, up to the body or the attributes.
193        let end = after.find(['{', ' ']).unwrap_or(after.len());
194        &after[..end]
195    };
196    Ok((inputs, tensor_types(results)?))
197}
198
199/// The position of the parenthesis that closes an opened one, skipping
200/// string literals (such as in `loc("...")`).
201fn closing_paren(s: &str) -> Option<usize> {
202    let mut depth = 0usize;
203    let mut in_string = false;
204    let mut escaped = false;
205    for (i, c) in s.char_indices() {
206        if in_string {
207            match c {
208                _ if escaped => escaped = false,
209                '\\' => escaped = true,
210                '"' => in_string = false,
211                _ => {}
212            }
213            continue;
214        }
215        match c {
216            '"' => in_string = true,
217            '(' => depth += 1,
218            ')' if depth == 0 => return Some(i),
219            ')' => depth -= 1,
220            _ => {}
221        }
222    }
223    None
224}
225
226/// The `tensor<...>` types in a piece of a signature, outside string
227/// literals.
228fn tensor_types(s: &str) -> Result<Vec<AVal>, ExternError> {
229    let mut out = Vec::new();
230    let mut in_string = false;
231    let bytes = s.as_bytes();
232    let mut i = 0;
233    while i < bytes.len() {
234        match bytes[i] {
235            b'"' => in_string = !in_string,
236            b't' if !in_string && s[i..].starts_with("tensor<") => {
237                let body_start = i + "tensor<".len();
238                let end = s[body_start..]
239                    .find('>')
240                    .ok_or_else(|| ExternError::Signature(format!("bad type in `{s}`")))?;
241                out.push(tensor_type(&s[body_start..body_start + end])?);
242                i = body_start + end;
243            }
244            _ => {}
245        }
246        i += 1;
247    }
248    Ok(out)
249}
250
251/// An abstract value from the body of a tensor type, such as `4x64xf32`.
252fn tensor_type(body: &str) -> Result<AVal, ExternError> {
253    let body = body.split(',').next().unwrap_or(body).trim();
254    let mut parts: Vec<&str> = body.split('x').collect();
255    let element = parts.pop().unwrap_or_default();
256    let dtype = match element {
257        "i1" => DType::Bool,
258        "i8" => DType::I8,
259        "i16" => DType::I16,
260        "i32" => DType::I32,
261        "i64" => DType::I64,
262        "ui8" => DType::U8,
263        "ui16" => DType::U16,
264        "ui32" => DType::U32,
265        "ui64" => DType::U64,
266        "f16" => DType::F16,
267        "bf16" => DType::BF16,
268        "f32" => DType::F32,
269        "f64" => DType::F64,
270        other => {
271            return Err(ExternError::Signature(format!(
272                "unsupported element type `{other}`"
273            )));
274        }
275    };
276    let dims = parts
277        .iter()
278        .map(|d| {
279            d.parse::<usize>().map_err(|_| {
280                ExternError::Signature(format!("unsupported dimension `{d}` in `tensor<{body}>`"))
281            })
282        })
283        .collect::<Result<Vec<_>, _>>()?;
284    Ok(AVal::new(dims, dtype))
285}
286
287#[cfg(test)]
288mod tests {
289    use super::*;
290
291    #[test]
292    fn reads_signatures_with_locations_and_attributes() {
293        let m = r#"module @m attributes {x = 1} {
294  func.func public @main(%arg0: tensor<64xf32> loc("v['a']"), %arg1: tensor<4x64xbf16> loc("(x)"), %arg2: tensor<i1>) -> (tensor<2xf32> {jax.result_info = "result[0]"}, tensor<ui8>) {
295    return
296  }
297}"#;
298        let (i, o) = signature(m).unwrap();
299        assert_eq!(
300            i,
301            [
302                AVal::new([64], DType::F32),
303                AVal::new([4, 64], DType::BF16),
304                AVal::scalar(DType::Bool)
305            ]
306        );
307        assert_eq!(o, [AVal::new([2], DType::F32), AVal::scalar(DType::U8)]);
308        let single = "func.func public @main(%x: tensor<3xf32>) -> tensor<3xf32> {";
309        assert_eq!(signature(single).unwrap().1, [AVal::new([3], DType::F32)]);
310        assert!(matches!(signature("module {}"), Err(ExternError::NoMain)));
311    }
312}