Skip to main content

ruxla_nn/
model.rs

1//! Models written by `ruxla.export_model` in Python.
2
3use std::path::Path;
4
5use ruxla_core::{Array, Element, ExternError, ExternFn, Native, Trace, Tree};
6use serde_json::Value;
7
8use crate::weights::{Weights, WeightsError};
9
10/// An error from loading an [`ExportedModel`].
11#[derive(Debug, thiserror::Error)]
12#[non_exhaustive]
13pub enum ModelError {
14    /// A file could not be read.
15    #[error("cannot read `{path}`: {source}")]
16    Io {
17        /// The file.
18        path: String,
19        /// The error.
20        source: std::io::Error,
21    },
22    /// The manifest is not what `ruxla.export_model` writes.
23    #[error("invalid manifest: {0}")]
24    Manifest(String),
25    /// The weights could not be read.
26    #[error(transparent)]
27    Weights(#[from] WeightsError),
28    /// The module could not be read.
29    #[error(transparent)]
30    Extern(#[from] ExternError),
31}
32
33/// A JAX model written by `ruxla.export_model(fn, params, *args, path=...)`:
34/// its parameters ([`Weights`], for Rust layers written like the model) and
35/// the function exported with `jax.export` ([`ExternFn`], called with the
36/// parameters and then the other arguments, with XLA).
37#[derive(Clone, Debug)]
38pub struct ExportedModel {
39    /// The exported function.
40    pub function: ExternFn,
41    /// The parameters, named by their path in the parameter tree.
42    pub weights: Weights,
43    param_names: Vec<String>,
44    num_args: usize,
45}
46
47impl ExportedModel {
48    /// Reads the directory written by `ruxla.export_model`.
49    ///
50    /// # Errors
51    ///
52    /// Returns an error if a file cannot be read or does not match the
53    /// others.
54    pub fn load(dir: impl AsRef<Path>) -> Result<Self, ModelError> {
55        let dir = dir.as_ref();
56        let read = |name: &str| {
57            let path = dir.join(name);
58            std::fs::read(&path).map_err(|source| ModelError::Io {
59                path: path.display().to_string(),
60                source,
61            })
62        };
63        let manifest: Value = serde_json::from_slice(&read("manifest.json")?)
64            .map_err(|e| ModelError::Manifest(e.to_string()))?;
65        if manifest["kind"] != "model" || manifest["schema_version"] != 1 {
66            return Err(ModelError::Manifest(String::from(
67                "not a model of schema version 1",
68            )));
69        }
70        let param_names: Vec<String> = manifest["param_names"]
71            .as_array()
72            .ok_or_else(|| ModelError::Manifest(String::from("no parameter names")))?
73            .iter()
74            .map(|v| v.as_str().map(String::from))
75            .collect::<Option<_>>()
76            .ok_or_else(|| {
77                ModelError::Manifest(String::from("a parameter name is not a string"))
78            })?;
79        let num_args = manifest["num_args"]
80            .as_u64()
81            .ok_or_else(|| ModelError::Manifest(String::from("no number of arguments")))?
82            as usize;
83        let weights = Weights::from_safetensors(&read("weights.safetensors")?)?;
84        let module = String::from_utf8(read("model.mlir")?)
85            .map_err(|_| ModelError::Manifest(String::from("model.mlir is not UTF-8")))?;
86        let name = dir.file_name().map_or_else(
87            || String::from("model"),
88            |n| n.to_string_lossy().into_owned(),
89        );
90        let mut function = ExternFn::from_mlir(name.clone(), module)?;
91        // The VJP written by `export_model`, if any: the model is then
92        // differentiable in reverse mode.
93        if let Ok(vjp) = std::fs::read(dir.join("model_vjp.mlir")) {
94            let vjp = String::from_utf8(vjp)
95                .map_err(|_| ModelError::Manifest(String::from("model_vjp.mlir is not UTF-8")))?;
96            function = function.with_vjp(ExternFn::from_mlir(format!("{name}_vjp"), vjp)?)?;
97        }
98        if function.inputs().len() != param_names.len() + num_args {
99            return Err(ModelError::Manifest(format!(
100                "the function takes {} arrays, but there are {} parameters and {num_args} arguments",
101                function.inputs().len(),
102                param_names.len()
103            )));
104        }
105        for (i, n) in param_names.iter().enumerate() {
106            let w = weights.get(n)?;
107            if w.aval() != function.inputs()[i] {
108                return Err(ModelError::Manifest(format!(
109                    "the parameter `{n}` is {}, but the function takes {}",
110                    w.aval(),
111                    function.inputs()[i]
112                )));
113            }
114        }
115        Ok(Self {
116            function,
117            weights,
118            param_names,
119            num_args,
120        })
121    }
122
123    /// The names of the parameters, in the order the function takes them.
124    pub fn param_names(&self) -> &[String] {
125        &self.param_names
126    }
127
128    /// The number of arguments after the parameters.
129    pub fn num_args(&self) -> usize {
130        self.num_args
131    }
132
133    /// The parameters in the order the function takes them, as native arrays
134    /// of type `T`.
135    ///
136    /// # Errors
137    ///
138    /// Returns an error if a parameter has another type.
139    pub fn params<T: Element>(&self) -> Result<Vec<Array<Native, T>>, WeightsError> {
140        self.param_names
141            .iter()
142            .map(|n| self.weights.array(n, self.weights.get(n)?.shape()))
143            .collect()
144    }
145
146    /// Calls the function on `params` (in the order of
147    /// [`ExportedModel::param_names`]) and the leaves of `args`, inside a
148    /// trace, returning the outputs in the structure of `like` (see
149    /// [`ExternFn::call`]).
150    ///
151    /// # Panics
152    ///
153    /// Panics if the arguments or `like` do not have the function's types.
154    #[track_caller]
155    pub fn call<T: Element, A: Tree<Trace>, O: Tree<Native>>(
156        &self,
157        params: &[Array<Trace, T>],
158        args: &A,
159        like: &O,
160    ) -> O::On<Trace> {
161        self.function.call(&(params.to_vec(), args.clone()), like)
162    }
163}