1use 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#[derive(Debug, thiserror::Error)]
15#[non_exhaustive]
16pub enum ExternError {
17 #[error("the module has no public `main` function")]
19 NoMain,
20 #[error("cannot read the signature of `main`: {0}")]
22 Signature(String),
23}
24
25#[derive(Clone)]
49pub struct ExternFn {
50 name: String,
51 module: Arc<str>,
52 inputs: Vec<AVal>,
53 outputs: Vec<AVal>,
54 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 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 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 pub fn inputs(&self) -> &[AVal] {
117 &self.inputs
118 }
119
120 pub fn outputs(&self) -> &[AVal] {
122 &self.outputs
123 }
124
125 #[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 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 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
172fn 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 let end = after.find(['{', ' ']).unwrap_or(after.len());
194 &after[..end]
195 };
196 Ok((inputs, tensor_types(results)?))
197}
198
199fn 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
226fn 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
251fn 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}