Skip to content

Importing JAX environments

ruxla's IR has the primitives, parameters, and static shapes of JAX's jaxprs. An environment written in JAX can therefore be imported from its jaxpr, without rewriting it in Rust, and run with ruxla's interpreter or compiled ahead of time to native code.

JAX function (Python)
   │  ruxla.export_jaxpr(fn, *args): trace with jax.make_jaxpr, rewrite into
   │  ruxla's primitives
   ▼
JSON document (one entry per equation: primitive, input and output types, parameters)
   │  ruxla_import::from_json: build a Function and type-check it
   ▼
ruxla_ir::Function (no different from IR traced from Rust)
   │  interpreter / optimization and code generation / XLA
   ▼
CompiledEnv Rust code (ruxla_env::compiled::generate_from_functions)

The repository's export script supports gymnax, Pgx, and Jumanji by default, and on request Craftax, Brax, MuJoCo Playground, NAVIX, XLand-MiniGrid, JaxMARL, and Waymax (Optional libraries); other libraries can be exported with a small wrapper (Other libraries).

gymnax with JAX 0.12

gymnax 1.0 asks for an older JAX. Install its dependencies with JAX pinned, then gymnax without dependencies: pip install "jax==0.12.*" flax chex six and pip install --no-deps "gymnax==1.0.*".

Exporting a function

import jax.numpy as jnp
import ruxla

doc = ruxla.export_jaxpr(lambda x: jnp.sin(x) * 2, jnp.zeros(3))   # a JSON string

The inputs and outputs are the leaves of the argument and result pytrees, in order; typed keys become their raw uint32[..., 2] data. Rust reads the document with ruxla_import::from_json:

let doc = r#"{"format_version": 1, "function": {
    "invars": [{"id": 0, "dtype": "f32", "shape": [2]}], "constvars": [],
    "eqns": [{"prim": "sin", "inputs": [{"var": 0}],
              "outputs": [{"id": 1, "dtype": "f32", "shape": [2]}],
              "params": {"accuracy": null}}],
    "outvars": [{"var": 1}]}}"#;
let f = ruxla_import::from_json(doc).unwrap();
assert_eq!(f.to_string(), "{ lambda ; a:f32[2]. let\n    b:f32[2] = sin a\n  in (b,) }");

What the rewriting does

The Python side (python/ruxla/_jaxpr.py) re-traces the jaxpr with an interpreter and rewrites what ruxla does not have:

In the jaxpr Rewritten as
jit, closed_call, checkpoint, custom_jvp_call, custom_vjp_call Inlined (imported functions are not differentiated, so custom rules are dropped)
custom_linear_solve (jnp.linalg.solve, ...) The solve jaxpr applied to the right-hand side
Typed keys and random_* primitives Raw uint32 key data and JAX's own threefry implementation
High-level primitives (call_hi_primitive, such as nonzero) Their own lowering
squeeze, stack, unstack, tile, split, copy, stop_gradient, device_put, ... lax reshapes, broadcasts, concatenations, slices (or the identity)
empty, add_any Zeros, add
asin, acos, atan atan2 and sqrt, as XLA decomposes them
Boolean reduce_and/reduce_or/reduce_xor, integer reduce_xor, reduce_prod Other reductions and folds
cond, while, scan Re-traced (bodies rewritten too); a batched while predicate becomes a loop on any lane with a select, as JAX lowers it

The Rust side (ruxla-import) maps each primitive by name and its parameters to ruxla's, inserts broadcasts where JAX 0.12 broadcasts scalars implicitly, and type-checks the result.

Exporting an environment

ruxla.export_env(path, *, name, reset, step, key, action, action_space, legal_action_mask=None) writes an environment to a directory:

  • reset(key) -> (obs, state) and step(key, state, action) -> (obs, state, reward, terminated, truncated, final_obs, discount) (the step with the automatic reset, like ruxla's Environment::step), on pytrees, with the parameters as constants;
  • key (a raw uint32[2] key) and action are examples;
  • action_space is {"kind": "discrete", "n": n}, {"kind": "multi_discrete", "nvec": [...]}, or {"kind": "box", "low": [...], "high": [...], "shape": [...]}.

It writes manifest.json, reset.json, step.json, and legal_action_mask.json (if given).

python -m ruxla.export

The package's exporter wraps each library's environments in this form and exports them, with a trajectory recorded by JAX (jit, CPU), to .cache/jax-envs/<module>/ in the working directory (large). The libraries must be installed in the Python environment. From Python, ruxla.export.export_envs(envs, out=..., steps=..., rollout_steps=...) does the same and returns the exported directories.

JAX_PLATFORMS=cpu .venv/bin/python -m ruxla.export [--steps N] [--rollout N] [--out DIR] [envs...]

Environments are named library:name, for example gymnax:CartPole-v1, pgx:tic_tac_toe, or jumanji:Snake-v1; a library name alone (gymnax, pgx, jumanji) selects all of its environments. Without arguments, it exports gymnax:CartPole-v1.

Option Default Meaning
--steps N 40 Steps of the recorded trajectory (trajectory.json)
--rollout N 1000 Steps of the long rollout summary (rollout.json); 0 writes none
--out DIR .cache/jax-envs Output directory
Library How the script wraps it
gymnax env.step(key, state, action, params) (gymnax 1.0's step with automatic reset). MNISTBandit is not exported (its images would be a 47 MB constant)
Pgx The form of pgx.experimental.auto_reset: the whole Pgx state, the observation, the acting player's reward, and legal_action_mask
Jumanji The whole Jumanji state and the timestep's observation, with a gymnax-style reset on episode end; the rewards of several agents are summed (as Jumanji's MultiToSingleWrapper). Sokoban uses the two-level ToyGenerator

Optional libraries

These libraries are exported only when named on the command line, and their packages are not dependencies of ruxla. A library name alone selects the environments listed below (for NAVIX, XLand-MiniGrid, and JaxMARL, every registered environment); any other environment of the library can be named as library:name.

Library Wrapper Environments by default How the script wraps it
Craftax ruxla.export.extra Craftax-Classic-Symbolic-v1, Craftax-Symbolic-v1 The environment without its own reset, reset in gymnax's form; reaching max_timesteps is a truncation
Brax ruxla.export.extra ant, humanoid The MJX backend with Brax's 1000-step time limit (EpisodeWrapper)
MuJoCo Playground ruxla.export.extra Go1JoystickFlatTerrain, G1JoystickFlatTerrain, LeapCubeReorient, Go1Handstand, Go1Getup, SpotGetup MJX's JAX implementation (impl: jax) with Playground's episode_length
NAVIX ruxla.export.suites all registered NAVIX's automatic reset disabled (it defers the reset by one step); the end from the step type
XLand-MiniGrid ruxla.export.suites all registered The default parameters
JaxMARL ruxla.export.suites all registered All agents' actions as one multi-discrete action (or one concatenated box), rewards summed over agents
Waymax ruxla.export.waymax PlanningAgent-IDM-v0 One scenario, the self-driving car with the invertible bicycle model, the other objects on IDM along their routes; the end of the log is a truncation

Craftax, Brax, and MuJoCo Playground install into the same environment as ruxla (JAX 0.12). Playground 0.2 calls jnp.clip with keywords that JAX 0.12 removed; the wrapper maps them.

uv pip install --python .venv craftax brax playground
JAX_PLATFORMS=cpu .venv/bin/python -m ruxla.export craftax brax:ant playground:Go1Handstand

NAVIX, XLand-MiniGrid, and JaxMARL pin other versions of JAX's libraries, so they go into an environment of their own with the same JAX, and ruxla installed without its dependencies:

uv venv .venv-suites --python 3.13
uv pip install --python .venv-suites "jax==0.12.*" flax chex jaxtyping pillow tqdm matplotlib wandb dm-env six absl-py
uv pip install --python .venv-suites --no-deps navix xminigrid jaxmarl rlax distrax tfp-nightly ruxla
JAX_PLATFORMS=cpu .venv-suites/bin/python -m ruxla.export navix xminigrid jaxmarl

The physics environments (Brax, Playground) and Craftax generate large Rust modules: compiling one takes from tens of seconds to a few minutes and several GB of memory. Their trajectories are compared with a looser tolerance (MJX's constraint solver amplifies rounding differences; JAX itself differs by up to 1e-2 between jit and op-by-op execution), only on the integrated state, the observation, and the reward, and without a long rollout. LeapCubeReorient is exported but not compared: MJX's convex collision breaks ties by rounding.

Waymax

Waymax is not on PyPI, its data loader uses TensorFlow, and its scenarios come from the Waymo Open Motion Dataset, which cannot be redistributed. The wrapper (ruxla.export.waymax) is a minimal example: one scenario, with the self-driving car as the agent.

  1. Install Waymax and its dependencies:

    uv pip install --python .venv tensorflow dm-tree immutabledict mediapy dm-env
    uv pip install --python .venv --no-deps "git+https://github.com/waymo-research/waymax.git"
    
  2. Accept the dataset's terms at https://waymo.com/open/. Then either point RUXLA_WAYMAX_DATA at TFRecord files of the dataset with routes, or use the 20 scenarios of Waymax's tests, read from .cache/waymax/tfrecord_with_routes by default:

    mkdir -p .cache/waymax
    curl -L -o .cache/waymax/tfrecord_with_routes \
      https://github.com/waymo-research/waymax/raw/main/waymax/dataloader/testdata/tfrecord_with_routes
    
  3. Export, compile, and run it:

    JAX_PLATFORMS=cpu .venv/bin/python -m ruxla.export waymax
    RUXLA_JAX_ENVS_ONLY=waymax_planningagent_idm_v0 cargo test --release -p ruxla-env-jax -- --nocapture
    RUXLA_JAX_ENVS_ONLY=waymax_planningagent_idm_v0 cargo run --release -p ruxla-env-jax --example run -- waymax_planningagent_idm_v0 64
    

The reset is the first scenario of the data, and the automatic reset starts the scenario held in the state again. To train on many scenarios, load them with Waymax's data loader on the host and write another scenario into the state between episodes. On the GPU, import TensorFlow only after JAX has created its solver handle (the wrapper does a small solve first): TensorFlow loads its own CUDA libraries.

Module names

The module names are <library>_<name> in lowercase with runs of non-alphanumeric characters replaced by _ (for example gymnax_cartpole_v1, pgx_tic_tac_toe, jumanji_snake_v1).

Other libraries

Any JAX environment can be exported by writing the two functions in this form and passing them to ruxla.export_env. For example, for an environment with gymnax-like reset_env and step_env:

import jax, jax.numpy as jnp, ruxla

env, params = make_my_env()            # your library

def reset(key):
    return env.reset_env(key, params)  # (obs, state)

def step(key, state, action):
    key_step, key_reset = jax.random.split(key)
    obs, s, reward, done, info = env.step_env(key_step, state, action, params)
    obs_reset, s_reset = env.reset_env(key_reset, params)
    new_state = jax.tree.map(lambda a, b: jnp.where(done, a, b), s_reset, s)
    new_obs = jnp.where(done, obs_reset, obs)
    terminated, truncated = done, jnp.zeros((), bool)
    discount = jnp.where(terminated, 0.0, 1.0)
    return new_obs, new_state, reward, terminated, truncated, obs, discount

ruxla.export_env(
    ".cache/jax-envs/mylib_myenv", name="MyEnv-v0", reset=reset, step=step,
    key=jax.random.PRNGKey(0), action=jnp.int32(0), action_space={"kind": "discrete", "n": 4},
)

ruxla.compile_env and ruxla-build compile every exported directory, so the environment above becomes the module mylib_myenv. Its agreement test also needs a recorded trajectory.json; the functions record and rollout of ruxla.export show how to write it, and the optional wrappers (ruxla.export.extra, ruxla.export.suites, ruxla.export.waymax) are worked examples: a module with a LIBRARIES table, registered in OPTIONAL of ruxla/export/_core.py, adds a library to the exporter.

Compiling from Python: ruxla.compile_env

ruxla.compile_env compiles exported environments to a native shared library and loads it, without a clone of the repository. It needs a Rust toolchain (cargo, from https://rustup.rs):

import numpy as np, ruxla

compiled = ruxla.compile_env(["gymnax:CartPole-v1", "pgx:tic_tac_toe"])  # exports, then builds
envs = compiled.vec_env("gymnax_cartpole_v1", num_envs=1024, seed=0)     # a ruxla.VecEnv
obs = envs.reset()
obs, reward, terminated, truncated, info = envs.step(np.zeros(1024, np.int32))
  • envs is an exported directory, a directory of them (such as .cache/jax-envs), an environment library:name (or a library) to export first, or a list of these.
  • It writes a small crate to ~/.cache/ruxla/envs/<fingerprint>/ (or under RUXLA_CACHE_DIR) whose build script uses ruxla-build and whose library exports the environments through the C ABI of ruxla_env::dylib, and builds it with cargo build --release. The target directory is shared by all compilations: the first one compiles the ruxla crates (about two minutes), later ones only the environments, and a call with unchanged exports loads the library without building.
  • The ruxla crates come from source= or RUXLA_SOURCE (a local checkout, a git URL, or a version on crates.io), else from the checkout around the package, else from the release of the package's version, else from the GitHub repository.
  • compiled.modules lists the environments; ruxla.VecEnv(name, num_envs, library=compiled) (or the library's path) is the same as compiled.vec_env(name, num_envs).

Compiling in your own crate: ruxla-build

A Rust program compiles exported environments with ruxla-build in its build script:

[dependencies]
ruxla-env = "0.1"      # the generated code uses these three crates
ruxla-codegen = "0.1"
ruxla-ir = "0.1"

[build-dependencies]
ruxla-build = "0.1"

# The code generator runs in the build script: optimize it.
[profile.dev.build-override]
opt-level = 3
[profile.release.build-override]
opt-level = 3
// build.rs
fn main() {
    ruxla_build::compile_envs("envs"); // every exported directory under ./envs
}
// src/lib.rs (or main.rs)
ruxla_env::include_envs!();   // gymnax_cartpole_v1::Env, ..., MODULES, visit

// let mut envs = ruxla_env::CompiledVecEnv::new(gymnax_cartpole_v1::Env, 4096, 0);

compile_envs honours RUXLA_JAX_ENVS (another directory) and RUXLA_JAX_ENVS_ONLY (some modules); ruxla_build::Builder sets the directory, the modules, and the code generator's options explicitly. A cdylib that adds ruxla_env::export_vec_envs!(); can be loaded by programs built separately (ruxla_env::dylib::Library), which is what ruxla.compile_env does.

The template crate ruxla-env-jax

The repository's ruxla-env-jax is such a crate (ruxla_build::compile_envs in its build script), with the agreement tests and an example. ruxla_build reads every exported directory with ruxla_env::jax_env::load_functions and generates a CompiledEnv module for each with ruxla_env::compiled::generate_from_functions (with fast_math):

  • the directory is RUXLA_JAX_ENVS, or .cache/jax-envs at the repository root;
  • RUXLA_JAX_ENVS_ONLY (module names separated by commas) compiles only those;
  • without exported files, the crate has no environment (ruxla_env_jax::MODULES is empty) and its tests print that they skipped and pass.

ruxla-env-jax is not a default member of the workspace; build and test it in release mode:

JAX_PLATFORMS=cpu .venv/bin/python -m ruxla.export pgx:tic_tac_toe jumanji:Snake-v1
cargo test --release -p ruxla-env-jax -- --nocapture

The crate exposes MODULES (the compiled module names), DATA_DIR (the directory they were compiled from), and visit, which reaches an environment by module name through a Visitor (each compiled environment has its own type):

use ruxla_env::compiled::CompiledEnv;
use ruxla_env_jax::Visitor;

struct Name;
impl Visitor for Name {
    type Output = String;
    fn visit<E: CompiledEnv + Clone + 'static>(&mut self, _module: &str, env: &E) -> String {
        env.name().to_string()
    }
}

for module in ruxla_env_jax::MODULES {
    let name = ruxla_env_jax::visit(module, &mut Name);
    println!("{module}: {name:?}");
}

The example run steps a batch of an imported environment with CompiledVecEnv on all cores and prints the steps per second and the mean return of the episodes that ended:

cargo run --release -p ruxla-env-jax --example run -- <module> [num_envs] [steps]

Built into the extension module

Instead of ruxla.compile_env, the extension module can also be built from a clone with the environments of ruxla-env-jax inside (the feature jax-envs); ruxla.VecEnv then runs them by module name. The environments are chosen at build time (RUXLA_JAX_ENVS, RUXLA_JAX_ENVS_ONLY):

cd python && VIRTUAL_ENV=$PWD/../.venv ../.venv/bin/maturin develop --release --features jax-envs
import numpy as np, ruxla

envs = ruxla.VecEnv("gymnax_cartpole_v1", num_envs=1024, seed=0)
obs = envs.reset()
obs, reward, terminated, truncated, info = envs.step(np.zeros(1024, np.int32))

See Python VecEnv and Gymnasium.

Agreement tests

crates/ruxla-env-jax/tests/agree.rs replays the recorded trajectories step by step, with the imported functions on the interpreter and with the generated code (step and step_in_place), and compares them with JAX: integers and booleans exactly, floats within a relative tolerance of 1e-5 (or a tolerance recorded per environment). When rollout.json exists, it also follows JAX's long trajectory from the reset with the generated code, across episode ends, comparing a per-step summary.

On integer and boolean environments (MinAtar, board games, mazes, ...), the imported versions agree bit for bit; on float environments, last-bit differences come from XLA's FMAs and reciprocal multiplications.

Limits

  • The imported code keeps JAX's style (compute everything and select), so algorithmic shortcuts that a hand port can take do not apply.
  • Imported environments do not run on the eager Native backend: they run on the interpreter or compiled ahead of time.
  • Jumanji's legal action masks live in the observation and are not exported as functions of the state.
  • pure_callback, io_callback, and dynamic shapes cannot be imported. Very large constants (gymnax's MNIST images) are impractical.