ruxla environments in JAX¶
An environment (or any function) written with ruxla can be exported as IR and used inside JAX programs.
JAX sees it as one primitive, ruxla_call, whose rules are delegated to ruxla, so it works under
jax.jit, jax.vmap, jax.lax.scan, jax.pmap, and jax.shard_map, can be differentiated, and is
compiled by XLA together with the model.
Exporting from Rust¶
ruxla::env::export(&env, path) writes a .ruxlapkg package (a directory) with three functions,
traced with B = Trace from examples made natively (the default parameters and a reset state):
reset(key, params) -> (obs, state)step(key, state, action, params) -> (obs, state, reward, terminated, truncated, final_observation, discount)(with the automatic reset)default_params() -> params
and a manifest.json that records the pytree structure of each function's inputs and outputs, the
observation shape, and the action space.
The example export_env exports the reference environments by name (cartpole, acrobot, pendulum,
breakout, tic_tac_toe):
Packages of arbitrary functions¶
PackageWriter writes packages of any functions, which Python loads with ruxla.load:
use ruxla_core::{Array, Native, Trace, jnp};
let mut package = ruxla_env::PackageWriter::new("sin.ruxlapkg")?;
package.function(
"sin",
|x: Array<Trace, f32>| jnp::sin(&x),
&Array::<Native, f32>::from_vec(vec![0.0; 3], [3]),
)?;
package.finish("functions", serde_json::Map::new())?;
function(name, f, example) traces f on values shaped like example; finish(kind, extra) writes the
manifest. export uses the same writer with the kind env.
Loading in Python¶
import jax
import jax.numpy as jnp
import ruxla
env = ruxla.load_env("cartpole.ruxlapkg")
params = env.default_params
obs, state = env.reset(jax.random.key(0), params)
obs, state, reward, terminated, truncated, info = env.step(jax.random.key(1), state, 1, params)
# info: {"discount", "terminated", "truncated", "final_observation"}
load_env returns an Environment with gymnax 1.0's interface, so gymnax-based code (PureJaxRL, for
example) can use it unchanged. params is optional (it defaults to default_params). Keys can be typed
(jax.random.key) or raw uint32[2] key data. States and parameters are frozen dataclasses registered
as pytrees, with the field names of the Rust structs.
It composes with JAX's transformations like any JAX function:
n = 64
keys = jax.random.split(jax.random.key(1), n)
obs, states = jax.vmap(env.reset)(keys) # obs.shape == (n, 4)
batched = jax.jit(jax.vmap(env.step))(keys, states, jnp.arange(n) % 2)
Batching works for any batch size, nested vmaps, and batched parameters:
params = env.default_params
lengths = jnp.array([0.25, 0.5, 1.0], jnp.float32)
batched_params = jax.tree.map(lambda x: jnp.broadcast_to(x, (3,) + jnp.shape(x)), params)
batched_params = type(params)(**{**vars(batched_params), "length": lengths})
For environments with legal actions (the Pgx ports), env.legal_action_mask(state) returns the mask, or
None if the package has none.
Packages of arbitrary functions load with ruxla.load(path); each function is called with and returns
pytrees:
How ruxla_call works¶
| Rule | What ruxla does |
|---|---|
| Abstract evaluation | Returns the output types of the IR. Inside shard_map, the varying mesh axes of the inputs are carried to the outputs |
| Batching | JAX's vmap is answered with ruxla's own vmap (an IR transformation) for the batch size at hand |
| Lowering | ruxla emits StableHLO, which is merged into the module JAX compiles: XLA inlines the call and optimizes it together with the model. Linear algebra lowers to the same custom calls JAX uses (LAPACK on CPU, cuSOLVER on GPU) |
| JVP | ruxla linearizes the function (jvp and partial evaluation) into a primal function and a linear function, both called through ruxla_call again, so every rule applies to them too |
| Transpose | ruxla transposes the linear function; zero cotangents (including float0 for integer outputs) become zero arrays |
Because the IR has the same primitives as JAX's jaxprs (the batching rules, the threefry random numbers,
and jnp are written the way JAX writes them), an environment written with ruxla compiles to the same
kind of HLO as the same environment written in JAX. For the CartPole port, the PureJaxRL PPO learning
curve matched gymnax bit for bit and the optimized HLO differed only by a few bitcasts, constants, and
parameters.
Differentiating through ruxla functions¶
jax.grad, jax.jvp, jax.vjp, jax.linearize, jax.linear_transpose, and jax.hessian work on
functions that call ruxla, also under jit, vmap, scan, pmap, and shard_map. The repository's
tests compare them with the same computation written in jax.numpy (and Flax) and with finite
differences (python/tests/test_grad.py):
f = package["mixed"] # a ruxla function with float and integer inputs
def loss(x, y):
a, b, _, d = f(jnp.tanh(x) * 2.0, y, N)
return jnp.sum(a**2) + b * jnp.mean(d)
gx, gy = jax.grad(loss, (0, 1))(X, Y)
per_example = jax.jit(jax.vmap(jax.grad(loss), (0, None)))(xs, Y)
Integer outputs have float0 tangents, as in JAX.
Agreement with gymnax¶
The reference ports of gymnax environments use the same operations, dtypes, and random number draws as
gymnax. Inside JAX, jit(scan(step)) trajectories of the exported CartPole match gymnax bit for bit, and
the repository's Python tests check jit, vmap, scan, pmap, and shard_map against gymnax
(python/tests/test_cartpole.py, test_minatar_envs.py, test_continuous_envs.py).
Note
The JAX parts of the package live in python/ruxla/_primitive.py, the only module that uses JAX's
extension APIs (jax.extend, jax.interpreters). They target JAX 0.12.x.