ruxla-core 0.1.0

Internal crate of ruxla (use the `ruxla` crate): the frontend of ruxla (backend-generic values, native and tracing backends)
Documentation
//! Calling StableHLO modules written by other programs, such as JAX models
//! exported with `jax.export`.

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};

/// An error from reading a module for [`ExternFn`].
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ExternError {
    /// The module has no public `main` function.
    #[error("the module has no public `main` function")]
    NoMain,
    /// The signature of `main` could not be read.
    #[error("cannot read the signature of `main`: {0}")]
    Signature(String),
}

/// A StableHLO module written by another program, called like a function
/// from traced programs: XLA links it with the caller and compiles them
/// together (`extern_call`). The interpreter and the native backend cannot
/// run it, so programs that call it run with [`jit`](crate::jit).
///
/// # Examples
///
/// ```
/// use ruxla_core::{Array, ExternFn, Native, Trace, make_ir};
///
/// let module = r#"
/// module @jit_f {
///   func.func public @main(%x: tensor<2xf32>) -> (tensor<2xf32>) {
///     %0 = stablehlo.multiply %x, %x : tensor<2xf32>
///     return %0 : tensor<2xf32>
///   }
/// }
/// "#;
/// let f = ExternFn::from_mlir("square", module).unwrap();
/// let like = Array::<Native, f32>::from_vec(vec![0.0; 2], [2]);
/// let ir = make_ir(|x: Array<Trace, f32>| f.call(&x, &like), &like);
/// assert!(ir.to_string().contains("extern_call[name=square"));
/// ```
#[derive(Clone)]
pub struct ExternFn {
    name: String,
    module: Arc<str>,
    inputs: Vec<AVal>,
    outputs: Vec<AVal>,
    /// The VJP of the function, if given ([`ExternFn::with_vjp`]).
    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 {
    /// Reads a module in the MLIR text format (such as
    /// `jax.export.Exported.mlir_module()`), whose public `main` is the
    /// function; `name` names it in the IR and in the linked module.
    ///
    /// # Errors
    ///
    /// Returns an error if the module has no public `main` or its signature
    /// has types that ruxla does not have.
    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,
        })
    }

    /// Makes the function differentiable in reverse mode with its VJP: a
    /// module that takes the inputs and a cotangent for each output and
    /// returns a cotangent for each input, such as the one that
    /// `jax.export`'s `Exported.vjp()` writes. The call is then a
    /// `custom_vjp_call` whose backward function calls the VJP.
    ///
    /// # Errors
    ///
    /// Returns an error if the VJP does not have the signature that the
    /// function requires.
    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)
    }

    /// The types of the inputs of `main`.
    pub fn inputs(&self) -> &[AVal] {
        &self.inputs
    }

    /// The types of the outputs of `main`.
    pub fn outputs(&self) -> &[AVal] {
        &self.outputs
    }

    /// Calls the module on the leaves of `input` and returns its outputs in
    /// the structure of `like` (a pytree of native values of the output
    /// types, whose values are not used).
    ///
    /// # Panics
    ///
    /// Panics if the leaves of `input` or `like` do not have the types of the
    /// module's inputs or 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());
        };
        // `custom_vjp` with the inputs as residuals; the backward function
        // calls the VJP on the inputs and the cotangents.
        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())
    }

    /// Adds an `extern_call` of the module to the current trace.
    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(),
            },
        )
    }
}

/// Reads the input and output types of the public `main` of a module.
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 {
        // A single result type, up to the body or the attributes.
        let end = after.find(['{', ' ']).unwrap_or(after.len());
        &after[..end]
    };
    Ok((inputs, tensor_types(results)?))
}

/// The position of the parenthesis that closes an opened one, skipping
/// string literals (such as in `loc("...")`).
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
}

/// The `tensor<...>` types in a piece of a signature, outside string
/// literals.
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)
}

/// An abstract value from the body of a tensor type, such as `4x64xf32`.
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)));
    }
}