use std::fmt;
use std::sync::Arc;
use ruxla_ir::{AVal, DType, Params};
use crate::backend::{Backend as _, Native, Trace};
use crate::trace::{self, TraceRef};
use crate::tree::{Tree, leaves};
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ExternError {
#[error("the module has no public `main` function")]
NoMain,
#[error("cannot read the signature of `main`: {0}")]
Signature(String),
}
#[derive(Clone)]
pub struct ExternFn {
name: String,
module: Arc<str>,
inputs: Vec<AVal>,
outputs: Vec<AVal>,
vjp: Option<Arc<ExternFn>>,
}
impl fmt::Debug for ExternFn {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ExternFn")
.field("name", &self.name)
.field("inputs", &self.inputs)
.field("outputs", &self.outputs)
.finish_non_exhaustive()
}
}
impl ExternFn {
pub fn from_mlir(
name: impl Into<String>,
module: impl Into<String>,
) -> Result<Self, ExternError> {
let module: String = module.into();
let (inputs, outputs) = signature(&module)?;
Ok(Self {
name: name.into(),
module: module.into(),
inputs,
outputs,
vjp: None,
})
}
pub fn with_vjp(mut self, vjp: ExternFn) -> Result<Self, ExternError> {
let mut expected = self.inputs.clone();
expected.extend(self.outputs.iter().cloned());
if vjp.inputs != expected || vjp.outputs != self.inputs {
return Err(ExternError::Signature(format!(
"the VJP of `{}` must take {expected:?} and return {:?}, but takes {:?} and returns {:?}",
self.name, self.inputs, vjp.inputs, vjp.outputs
)));
}
self.vjp = Some(Arc::new(vjp));
Ok(self)
}
pub fn inputs(&self) -> &[AVal] {
&self.inputs
}
pub fn outputs(&self) -> &[AVal] {
&self.outputs
}
#[track_caller]
pub fn call<I: Tree<Trace>, O: Tree<Native>>(&self, input: &I, like: &O) -> O::On<Trace> {
let args: Vec<TraceRef> = leaves(input);
let out_avals: Vec<AVal> = leaves(like).iter().map(Native::leaf_aval).collect();
assert_eq!(
out_avals, self.outputs,
"`{}` returns {:?}, but the outputs are expected to be {out_avals:?}",
self.name, self.outputs
);
let Some(vjp) = &self.vjp else {
return like.rebuild::<Trace>(&mut self.bind(&args).into_iter());
};
let f = |x: I| like.rebuild::<Trace>(&mut self.bind(&leaves(&x)).into_iter());
let fwd = |x: I| (f(x.clone()), x);
let bwd = |x: I, ct: O::On<Trace>| {
let mut vjp_args = leaves(&x);
vjp_args.extend(leaves(&ct));
x.unflatten_like(&mut vjp.bind(&vjp_args).into_iter())
};
crate::lax::custom_vjp(f, fwd, bwd, input.clone())
}
fn bind(&self, args: &[TraceRef]) -> Vec<TraceRef> {
trace::bind(
ruxla_prims::EXTERN_CALL,
args,
Params::Extern {
name: self.name.clone(),
module: self.module.clone(),
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
},
)
}
}
fn signature(module: &str) -> Result<(Vec<AVal>, Vec<AVal>), ExternError> {
let start = ["func.func public @main(", "func.func @main("]
.iter()
.find_map(|p| module.find(p).map(|i| i + p.len()))
.ok_or(ExternError::NoMain)?;
let rest = &module[start..];
let args_end = closing_paren(rest)
.ok_or_else(|| ExternError::Signature(String::from("unbalanced parentheses")))?;
let inputs = tensor_types(&rest[..args_end])?;
let after = rest[args_end + 1..].trim_start();
let after = after
.strip_prefix("->")
.ok_or_else(|| ExternError::Signature(String::from("no results")))?
.trim_start();
let results = if let Some(r) = after.strip_prefix('(') {
let end = closing_paren(r)
.ok_or_else(|| ExternError::Signature(String::from("unbalanced parentheses")))?;
&r[..end]
} else {
let end = after.find(['{', ' ']).unwrap_or(after.len());
&after[..end]
};
Ok((inputs, tensor_types(results)?))
}
fn closing_paren(s: &str) -> Option<usize> {
let mut depth = 0usize;
let mut in_string = false;
let mut escaped = false;
for (i, c) in s.char_indices() {
if in_string {
match c {
_ if escaped => escaped = false,
'\\' => escaped = true,
'"' => in_string = false,
_ => {}
}
continue;
}
match c {
'"' => in_string = true,
'(' => depth += 1,
')' if depth == 0 => return Some(i),
')' => depth -= 1,
_ => {}
}
}
None
}
fn tensor_types(s: &str) -> Result<Vec<AVal>, ExternError> {
let mut out = Vec::new();
let mut in_string = false;
let bytes = s.as_bytes();
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'"' => in_string = !in_string,
b't' if !in_string && s[i..].starts_with("tensor<") => {
let body_start = i + "tensor<".len();
let end = s[body_start..]
.find('>')
.ok_or_else(|| ExternError::Signature(format!("bad type in `{s}`")))?;
out.push(tensor_type(&s[body_start..body_start + end])?);
i = body_start + end;
}
_ => {}
}
i += 1;
}
Ok(out)
}
fn tensor_type(body: &str) -> Result<AVal, ExternError> {
let body = body.split(',').next().unwrap_or(body).trim();
let mut parts: Vec<&str> = body.split('x').collect();
let element = parts.pop().unwrap_or_default();
let dtype = match element {
"i1" => DType::Bool,
"i8" => DType::I8,
"i16" => DType::I16,
"i32" => DType::I32,
"i64" => DType::I64,
"ui8" => DType::U8,
"ui16" => DType::U16,
"ui32" => DType::U32,
"ui64" => DType::U64,
"f16" => DType::F16,
"bf16" => DType::BF16,
"f32" => DType::F32,
"f64" => DType::F64,
other => {
return Err(ExternError::Signature(format!(
"unsupported element type `{other}`"
)));
}
};
let dims = parts
.iter()
.map(|d| {
d.parse::<usize>().map_err(|_| {
ExternError::Signature(format!("unsupported dimension `{d}` in `tensor<{body}>`"))
})
})
.collect::<Result<Vec<_>, _>>()?;
Ok(AVal::new(dims, dtype))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_signatures_with_locations_and_attributes() {
let m = r#"module @m attributes {x = 1} {
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>) {
return
}
}"#;
let (i, o) = signature(m).unwrap();
assert_eq!(
i,
[
AVal::new([64], DType::F32),
AVal::new([4, 64], DType::BF16),
AVal::scalar(DType::Bool)
]
);
assert_eq!(o, [AVal::new([2], DType::F32), AVal::scalar(DType::U8)]);
let single = "func.func public @main(%x: tensor<3xf32>) -> tensor<3xf32> {";
assert_eq!(signature(single).unwrap().1, [AVal::new([3], DType::F32)]);
assert!(matches!(signature("module {}"), Err(ExternError::NoMain)));
}
}