Skip to content

Quickstart

This page walks through the whole loop: an environment written once in Rust, run natively, run in parallel with VecEnv, and exported to JAX, where it works under jax.jit and jax.vmap.

It assumes a crate that depends on ruxla (see Installation).

1. A first environment

An environment implements the Environment trait with methods that are generic over the backend B. The code below is ruxla's own CartPole (crates/ruxla-env/src/cartpole.rs, a faithful port of gymnax's CartPole-v1), with the imports a user crate would write and a few parameters elided.

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

/// The state of an episode: a pytree of scalars.
#[derive(Clone, Debug, Tree)]
pub struct CartPoleState<B: Backend> {
    pub time: I32<B>,
    pub x: F32<B>,
    pub x_dot: F32<B>,
    pub theta: F32<B>,
    pub theta_dot: F32<B>,
}

/// The parameters (gymnax's `EnvParams`).
#[derive(Clone, Debug, Tree)]
pub struct CartPoleParams<B: Backend> {
    pub gravity: F32<B>,
    pub masspole: F32<B>,
    pub total_mass: F32<B>,
    pub length: F32<B>,
    pub polemass_length: F32<B>,
    pub force_mag: F32<B>,
    pub tau: F32<B>,
    pub theta_threshold_radians: F32<B>,
    pub x_threshold: F32<B>,
    pub max_steps_in_episode: I32<B>,
    // ...
}

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

impl CartPole {
    fn observation<B: Backend>(&self, s: &CartPoleState<B>) -> Array<B, f32> {
        jnp::stack(&[s.x, s.x_dot, s.theta, s.theta_dot], 0)
    }

    fn is_terminated<B: Backend>(&self, s: &CartPoleState<B>, p: &CartPoleParams<B>) -> Bool<B> {
        let done1 = s.x.lt(-p.x_threshold) | s.x.gt(p.x_threshold);
        let done2 = s.theta.lt(-p.theta_threshold_radians) | s.theta.gt(p.theta_threshold_radians);
        done1 | done2
    }
}

impl Environment for CartPole {
    type State<B: Backend> = CartPoleState<B>;
    type Params<B: Backend> = CartPoleParams<B>;
    type Obs<B: Backend> = Array<B, f32>;
    type Action<B: Backend> = I32<B>;

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

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

    fn default_params<B: Backend>(&self) -> CartPoleParams<B> {
        CartPoleParams {
            gravity: F32::new(9.8),
            force_mag: F32::new(10.0),
            tau: F32::new(0.02),
            max_steps_in_episode: I32::new(500),
            // ...
        }
    }

    fn reset<B: Backend>(
        &self,
        key: Key<B>,
        _params: &CartPoleParams<B>,
    ) -> (Array<B, f32>, CartPoleState<B>) {
        let init = random::uniform(&key, [4], -0.05f32, 0.05f32);
        let part = |i: i64| init.i(i).to_scalar();
        let state = CartPoleState {
            time: I32::new(0),
            x: part(0),
            x_dot: part(1),
            theta: part(2),
            theta_dot: part(3),
        };
        (self.observation(&state), state)
    }

    fn step_env<B: Backend>(
        &self,
        _key: Key<B>,
        s: &CartPoleState<B>,
        action: I32<B>,
        p: &CartPoleParams<B>,
    ) -> Transition<B, CartPoleState<B>, Array<B, f32>> {
        let prev_terminal = self.is_terminated(s, p);
        let force = p.force_mag * action.cast::<f32>() - p.force_mag * (1 - action).cast::<f32>();
        let costheta = s.theta.cos();
        let sintheta = s.theta.sin();
        let temp =
            (force + p.polemass_length * s.theta_dot.integer_pow(2) * sintheta) / p.total_mass;
        let thetaacc = (p.gravity * sintheta - costheta * temp)
            / (p.length
                * ((4.0f64 / 3.0) as f32 - p.masspole * costheta.integer_pow(2) / p.total_mass));
        let xacc = temp - p.polemass_length * thetaacc * costheta / p.total_mass;
        let next = CartPoleState {
            time: s.time + 1,
            x: s.x + p.tau * s.x_dot,
            x_dot: s.x_dot + p.tau * xacc,
            theta: s.theta + p.tau * s.theta_dot,
            theta_dot: s.theta_dot + p.tau * thetaacc,
        };
        let reward = 1.0 - prev_terminal.cast::<f32>();
        let terminated = self.is_terminated(&next, p);
        Transition { obs: self.observation(&next), state: next, reward, terminated }
    }

    fn step_env_uses_key(&self) -> bool {
        false
    }

    fn is_truncated<B: Backend>(&self, s: &CartPoleState<B>, p: &CartPoleParams<B>) -> Bool<B> {
        s.time.ge(p.max_steps_in_episode)
    }
}

Things to notice:

  • Arithmetic works on F32<B> with ordinary operators, and Rust literals take the type of the value (1.0 - x with x: F32<B> is an f32 operation). There is no implicit type promotion: conversions are explicit (action.cast::<f32>()).
  • Comparisons are methods (lt, gt, ge, eq) returning Bool<B>, because Rust's < must return bool. You cannot write if s.x > 0.0 on a value: data-dependent control flow goes through lax::select, lax::cond, and friends.
  • step (with gymnax's automatic reset) has a default implementation built from step_env, reset, and is_truncated.

The reference environments are available directly as ruxla::env::CartPole, ruxla::env::Breakout, and so on (see Environments); the rest of this page uses those.

2. Run it natively

With B = Native, the methods are plain Rust calls. This loop, adapted from the example crates/ruxla-nn/examples/cartpole_policy.rs, plays one episode with a fixed action:

use ruxla::prelude::*;
use ruxla::env::{CartPole, Environment};

let env = CartPole;
let params = env.default_params::<Native>();
let (mut key, reset_key) = random::split2(&random::key::<Native>(0));
let (_obs, mut state) = env.reset(reset_key, &params);
let mut total = 0.0;
for _ in 0..500 {
    let (next, step_key) = random::split2(&key);
    key = next;
    let st = env.step(step_key, &state, I32::new(1), &params);
    total += st.reward.value();
    if st.terminated.value() || st.truncated.value() {
        break;
    }
    state = st.state;
}
println!("return: {total}");

Natively, step computes the reset only when an episode ends, and .value() reads a native scalar.

3. Many environments in parallel: VecEnv

VecEnv steps a batch of native environments on a pool of worker threads and resets them automatically:

use ruxla::env::{CartPole, VecEnv};

let mut envs = VecEnv::new(CartPole, 8, 0);   // 8 environments, seed 0
let step = envs.step(&[1; 8]);                // one action per environment
assert_eq!(step.reward, [1.0; 8]);
assert_eq!(envs.obs_f32().len(), 8 * 4);

See Native execution and VecEnv for the buffers-based step_into, thread counts, and the ahead-of-time compiled CompiledVecEnv.

4. Use it in JAX

Export the environment as a .ruxlapkg package. This traces reset, step, and default_params with B = Trace:

ruxla::env::export(&ruxla::env::CartPole, "cartpole.ruxlapkg")?;

The repository has an example that does this for the reference environments:

cargo run -p ruxla-env --example export_env -- cartpole cartpole.ruxlapkg

Then load it in Python. The object has gymnax 1.0's interface, so code written for gymnax (such as PureJaxRL) can use it unchanged:

import jax
import jax.numpy as jnp
import ruxla

env = ruxla.load_env("cartpole.ruxlapkg")

# One environment.
key = jax.random.key(0)
obs, state = env.reset(key)
obs, state, reward, terminated, truncated, info = env.step(key, state, 1)

# Under jit and vmap, like any JAX function.
keys = jax.random.split(jax.random.key(1), 64)
obs, states = jax.vmap(env.reset)(keys)
step = jax.jit(jax.vmap(env.step))
obs, states, reward, terminated, truncated, info = step(keys, states, jnp.arange(64) % 2)

params defaults to env.default_params; pass a batched pytree of parameters to vmap over parameters too. Inside JAX the environment is the primitive ruxla_call: JAX's vmap batches it with ruxla's own vmap, and XLA compiles it together with the rest of the program. See ruxla environments in JAX.

5. Or from Python with NumPy only

The reference environments are also available as a CPU vector environment that does not need JAX:

import numpy as np
import ruxla

envs = ruxla.VecEnv("CartPole-v1", num_envs=256, seed=0)
obs = envs.reset()
actions = np.random.randint(0, envs.num_actions, envs.num_envs)
obs, reward, terminated, truncated, info = envs.step(actions)

See Python VecEnv and Gymnasium.

6. Train a PyTorch agent

The arrays of VecEnv go straight into PyTorch, with the agent on the GPU and the environments on CPU threads:

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()

See Using ruxla from PyTorch for a loop without per-step allocations (step_into with pinned tensors) and the complete PPO example.