JAX models in Rust¶
A policy trained in JAX can run in Rust next to a ruxla environment. There are two ways:
| Method | How | Pros | Cons |
|---|---|---|---|
| 1. Load the weights | Write the same architecture with ruxla::nn (Flax-compatible layers) and load the weights (safetensors or Flax msgpack) |
Runs natively and with XLA; can be one function with the environment | The architecture is written again in Rust |
| 2. Link the StableHLO | Export the model with jax.export and call it from ruxla's IR as an external function (extern_call) |
Any model, with exactly JAX's results | Needs XLA; does not run natively or on the interpreter |
Exporting from JAX¶
ruxla.export_model(fn, params, *example_args, path=...) writes a directory that serves both methods:
weights.safetensors: the parameters, named by their path in the parameter tree (params/Dense_0/kernel);model.mlir:fn(params, *args)exported withjax.export, taking the parameters (in the order of the tree's leaves) and then the other arguments;model_vjp.mlir: its VJP, when JAX can differentiate it (used to differentiate the external call);manifest.json: the order of the parameters and the function's types.
import jax, jax.numpy as jnp, ruxla
ruxla.export_model(
network.apply, params, jax.ShapeDtypeStruct((4,), jnp.float32), path="ppo_cartpole_model"
)
export_model needs safetensors (and flatbuffers for jax.export's serialization) in the Python
environment. The example arguments can be arrays or jax.ShapeDtypeStructs.
Method 1: layers and weights¶
ruxla_nn::Dense computes what Flax's Dense computes (a dot_general over the last dimension plus the
bias), so the traced IR has the form of Flax's jaxpr. Weights reads safetensors
(Weights::from_safetensors) and Flax's msgpack (Weights::from_flax_msgpack, the format of
flax.serialization.to_bytes).
This is the example crates/ruxla-nn/examples/cartpole_policy.rs: PureJaxRL's actor for CartPole,
written with ruxla and loaded from the weights of a PPO run in JAX.
use ruxla_core::random;
use ruxla_core::{Array, Backend, I32, Native, Trace, Tree, jit, jnp};
use ruxla_env::{CartPole, CartPoleParams, Environment};
use ruxla_nn::{Dense, Weights, tanh};
/// PureJaxRL's actor for CartPole (the critic is not needed to act).
#[derive(Clone, Debug, Tree)]
struct Actor<B: Backend> {
layers: [Dense<B>; 3],
}
impl<B: Backend> Actor<B> {
fn act(&self, obs: &Array<B, f32>) -> I32<B> {
let x = tanh(self.layers[0].apply(obs));
let x = tanh(self.layers[1].apply(&x));
jnp::argmax(self.layers[2].apply(&x), 0).to_scalar()
}
}
let weights = Weights::from_safetensors(&std::fs::read(path)?)?;
let actor = Actor::<Native> {
layers: std::array::from_fn(|i| {
Dense::load(&weights, &format!("params/Dense_{i}")).expect("load a layer")
}),
};
// Natively, with the environment in an ordinary loop:
let action = actor.act(&obs);
// With XLA, the same generic code compiled once:
let act = jit(|(a, obs): (Actor<Trace>, Array<Trace, f32>)| a.act(&obs));
let action = act.try_call(&(actor.clone(), obs.clone()));
Other layers follow Flax too: Conv (flax.linen.Conv, HWIO kernels, SAME/VALID/explicit padding,
strides, dilations, feature_group_count), LayerNorm, and the functions max_pool, min_pool,
avg_pool, relu, and tanh. Settings that are not part of the weights are given with builder methods,
for example Conv::load(&w, "params/Conv_0")?.strides(&[2, 2]).
Method 2: the exported function¶
ruxla_nn::ExportedModel::load(dir) reads the directory written by export_model. params::<f32>()
returns the parameters as native arrays in the order the function takes them, and
call(¶ms, &args, &like) calls the function inside a trace (with like giving the structure and
types of the outputs). The call becomes an extern_call equation that XLA links and compiles, so it runs
under jit and vmap(..).call_xla (batching turns it into a loop over examples):
use ruxla_core::{Array, Native, Shape, Trace};
let model = ruxla_nn::ExportedModel::load("ppo_cartpole_model")?;
let weights = model.params::<f32>()?;
let like = (
Array::<Native, f32>::from_vec(vec![0.0; 2], [2]), // logits
Array::<Native, f32>::from_vec(vec![0.0], Shape::scalar()), // value
);
let policy = ruxla_core::vmap(|(w, x): (Vec<Array<Trace, f32>>, Array<Trace, f32>)| {
model.call(&w, &x, &like)
});
let outs = policy.call_xla(&examples)?;
The lower-level ruxla::ExternFn::from_mlir(name, text) reads any jax.export module (its
mlir_module()); with_vjp attaches the exported VJP so that ruxla can differentiate the call (it
becomes a custom_vjp_call whose backward pass calls the VJP module).
Note
The tests check that the policy gives JAX's outputs (within 1e-5) natively, on the interpreter, and
with XLA, and that greedy rollouts in Rust reach the same returns (crates/ruxla-nn/tests/ppo_policy.rs).
Tests that need XLA are #[ignore] and require a PJRT plugin.