ruxla-kernels 0.1.0

Internal crate of ruxla (use the `ruxla` crate): semantics of ruxla's operations, shared by the native backend and the IR interpreter
Documentation
  • Coverage
  • 100%
    343 out of 343 items documented2 out of 134 items with examples
  • Size
  • Source code size: 482.0 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 4.3 MB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 8s Average build duration of successful builds.
  • all releases: 8s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • Homepage
  • ymgaq/ruxla
    0 0 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • ymgaq

English | 日本語 | 简体中文

ruxla runs reinforcement learning environments at native speed and keeps them compatible with JAX. Write an environment once in Rust, in the style of JAX, and run it as native code or export it into JAX, where it works under jit, vmap, and grad. Or take an environment already written in JAX, import it from its jaxpr, and compile it ahead of time to Rust, without rewriting it. ruxla is meant to be used together with JAX, not to replace it.

Performance

On 71 gymnax, Pgx, and Jumanji environments (Ryzen 9 9950X), imported environments run 11.2× faster than JAX with one environment and 6.5× faster with 4,096; against a stronger JAX baseline, 3.1× and 2.1×. With a compiled PyTorch PPO agent on the GPU and 8 or 64 environments, they raise training throughput over the best JAX backend by 1.4–5.8× on eight of nine tasks. See the benchmarks and the paper.

Why

  • Fast at small batches on CPUs. One to a few thousand environments on CPU cores (search, evaluation, actors) run as plain Rust close to handwritten speed, with no Python or XLA at run time.
  • One implementation for both worlds. The same Rust code runs natively and inside JAX, under jit, vmap, and grad.
  • Works with PyTorch. ruxla.VecEnv steps the environments on CPU threads and hands NumPy arrays to an agent on the GPU; with a PyTorch PPO agent, Craftax reaches its target 3× sooner than with JAX stepping it on the GPU.
  • No rewrite of JAX environments. gymnax, Pgx, Jumanji, and on request Craftax, Brax, MuJoCo Playground, NAVIX, XLand-MiniGrid, JaxMARL, and Waymax compile to Rust and match JAX's results.

Installation

pip install ruxla           # Python: ruxla.VecEnv with NumPy; "ruxla[jax]" adds the JAX parts (JAX 0.12)
cargo add ruxla             # Rust
cargo add --build ruxla-build   # Rust: compile environments exported from JAX in build.rs

Packages: PyPI · crates.io · API reference (docs.rs). ruxla.compile_env and ruxla-build also need a Rust toolchain (cargo).

Or build from a clone, the Python package with maturin:

git clone https://github.com/ymgaq/ruxla && cd ruxla
pip install "jax==0.12.*" maturin
cd python && maturin develop --release

Wheels are built for Linux (x86-64 and AArch64) and macOS on Apple silicon; Windows builds from source and is untested. Running XLA from Rust (jit) needs a PJRT plugin: ruxla downloads the CPU plugin on these three platforms (in a clone, scripts/fetch-pjrt-plugins.sh); everything else works without one. See the installation guide.

Quick examples

1. Write an environment in Rust and step it natively

use ruxla::env::{ActionSpace, Environment, Transition, VecEnv};
use ruxla::prelude::*;

/// A walk on a line: each step moves left or right; the episode ends at either end.
#[derive(Clone, Debug, Tree)]
pub struct WalkState<B: Backend> {
    pub x: F32<B>,
    pub time: I32<B>,
}

#[derive(Clone, Copy, Debug, Default)]
pub struct Walk;

impl Environment for Walk {
    type State<B: Backend> = WalkState<B>;
    type Params<B: Backend> = ();
    type Obs<B: Backend> = F32<B>;
    type Action<B: Backend> = I32<B>;

    fn name(&self) -> &str {
        "Walk"
    }

    fn action_space(&self) -> ActionSpace {
        ActionSpace::Discrete(2)
    }

    fn default_params<B: Backend>(&self) {}

    fn reset<B: Backend>(&self, key: Key<B>, _: &()) -> (F32<B>, WalkState<B>) {
        let x: F32<B> = random::uniform(&key, [], -1.0f32, 1.0f32).to_scalar();
        (x, WalkState { x, time: I32::new(0) })
    }

    fn step_env<B: Backend>(
        &self,
        key: Key<B>,
        s: &WalkState<B>,
        action: I32<B>,
        _: &(),
    ) -> Transition<B, WalkState<B>, F32<B>> {
        let noise: F32<B> = random::normal(&key, []).to_scalar();
        let x = s.x + action.cast::<f32>() * 2.0 - 1.0 + noise * 0.1;
        let terminated = x.gt(5.0) | x.lt(-5.0);
        let reward = lax::select(terminated, F32::new(1.0), F32::new(0.0));
        let state = WalkState { x, time: s.time + 1 };
        Transition { obs: x, state, reward, terminated }
    }

    fn is_truncated<B: Backend>(&self, s: &WalkState<B>, _: &()) -> Bool<B> {
        s.time.ge(100)
    }
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Natively: 1,024 walks stepped in parallel on all cores, with automatic resets.
    let mut envs = VecEnv::new(Walk, 1024, 0);
    let step = envs.step(&vec![1; 1024]);
    println!("reward of the first walk: {}", step.reward[0]);

    // As IR: a package for JAX.
    ruxla::env::export(&Walk, "walk.ruxlapkg")?;
    Ok(())
}

ruxla_env::compiled::generate compiles the same environment ahead of time to Rust for the fastest native code (guide); crates/ruxla-env-aot is a template.

2. Use it in JAX with jit, vmap, and grad

import jax
import jax.numpy as jnp
import ruxla

env = ruxla.load_env("walk.ruxlapkg")  # gymnax's API
keys = jax.random.split(jax.random.key(0), 4096)
obs, states = jax.vmap(env.reset)(keys)
step = jax.jit(jax.vmap(env.step))
obs, states, reward, terminated, truncated, info = step(keys, states, jnp.ones(4096, jnp.int32))

# Derivatives flow through the environment (here Pendulum, a reference environment
# exported with `cargo run -p ruxla-env --example export_env -- pendulum pendulum.ruxlapkg`).
pendulum = ruxla.load_env("pendulum.ruxlapkg")
key = jax.random.key(1)
_, state = pendulum.reset(key)
d_reward = jax.grad(lambda a: pendulum.step(key, state, a)[2])(jnp.array([0.5]))

Inside JAX the environment is the primitive ruxla_call, which XLA compiles together with the rest of the program (guide).

3. Import an existing JAX environment and run it natively

import numpy as np
import ruxla

# Export gymnax's CartPole (its jaxprs), compile it to native code with cargo, and load it.
compiled = ruxla.compile_env("gymnax:CartPole-v1")
envs = compiled.vec_env("gymnax_cartpole_v1", num_envs=4096, seed=0)  # NumPy, CPU threads
obs = envs.reset()
obs, reward, terminated, truncated, info = envs.step(np.zeros(4096, np.int32))

compile_env needs a Rust toolchain (cargo). In a Rust program, ruxla-build compiles the exported environments from the build script:

python -m ruxla.export gymnax:CartPole-v1 --out envs   # exported jaxprs in envs/gymnax_cartpole_v1
// build.rs (with ruxla-build as a build dependency)
fn main() { ruxla_build::compile_envs("envs"); }

// src/main.rs
ruxla_env::include_envs!();
use ruxla_env::compiled::{CompiledEnv, key, split_key};

fn main() {
    let env = gymnax_cartpole_v1::Env;
    let (_obs, mut state) = env.reset(key(0));
    let mut k = key(1);
    for t in 0..1000 {
        let (next, sub) = split_key(k);
        k = next;
        state = env.step(sub, &state, t % 2).state;
    }
}

See the guide for the other libraries (Craftax, Brax, MuJoCo Playground, NAVIX, XLand-MiniGrid, JaxMARL, Waymax).

4. Train a PyTorch agent

The environments come out as NumPy arrays, so any framework can learn from them. With PyTorch:

import torch, ruxla

envs = ruxla.VecEnv("Breakout-MinAtar", num_envs=64, seed=0)   # CPU threads, NumPy arrays
obs = torch.from_numpy(envs.reset()).cuda()
for t in range(1000):
    action = policy(obs)                                        # your PyTorch agent on the GPU
    obs, reward, terminated, truncated, info = envs.step(action.int().cpu().numpy())
    obs = torch.from_numpy(obs).cuda()

step_into writes into arrays you allocate once (pinned tensors give asynchronous copies to the GPU), and ruxla.compile_env(...).vec_env(...) gives the same VecEnv for an imported JAX environment such as Craftax. python/examples/ppo_torch.py is a complete CleanRL-style PPO, with an optional torch.compile agent; see Using ruxla from PyTorch.

Documentation

Citation

@misc{yamaguchi2026ruxla,
  title  = {ruxla: Native-Speed {JAX} Environments for Reinforcement Learning at Small Batch Sizes},
  author = {Yamaguchi, Yu},
  year   = {2026},
  url    = {https://ymgaq.github.io/ruxla/paper/ruxla.pdf},
  note   = {Preprint}
}

License

Apache License 2.0. See NOTICE for the parts derived from JAX and XLA.