Skip to content

Writing environments

Environments implement ruxla::env::Environment (crate ruxla-env), whose API follows gymnax 1.0. The methods are generic over the backend and must be pure functions of their arguments: the same code then runs natively, in parallel with VecEnv, with XLA through jit, inside JAX after export, and compiled ahead of time.

The trait

pub trait Environment: Send + Sync + 'static {
    type State<B: Backend>: Tree<B, /* ... */>;
    type Params<B: Backend>: Tree<B, /* ... */>;
    type Obs<B: Backend>: Tree<B, /* ... */>;
    /// `I32<B>` for discrete actions, `Array<B, i32>` for multi-discrete
    /// ones, `Array<B, f32>` for continuous ones.
    type Action<B: Backend>: Tree<B, /* ... */> + ActionValue<B> + Clone;

    fn name(&self) -> &str;
    fn action_space(&self) -> ActionSpace;
    fn num_actions(&self) -> usize { /* from action_space */ }
    fn default_params<B: Backend>(&self) -> Self::Params<B>;

    /// gymnax's `reset_env`.
    fn reset<B: Backend>(&self, key: Key<B>, params: &Self::Params<B>)
        -> (Self::Obs<B>, Self::State<B>);

    /// One step, without reset.
    fn step_env<B: Backend>(
        &self,
        key: Key<B>,
        state: &Self::State<B>,
        action: Self::Action<B>,
        params: &Self::Params<B>,
    ) -> Transition<B, Self::State<B>, Self::Obs<B>>;

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

    fn is_truncated<B: Backend>(&self, state: &Self::State<B>, params: &Self::Params<B>)
        -> Bool<B>;

    fn legal_action_mask<B: Backend>(&self, state: &Self::State<B>)
        -> Option<Array<B, bool>> { None }

    /// gymnax's `step`, with the automatic reset (provided).
    fn step<B: Backend>(
        &self,
        key: Key<B>,
        state: &Self::State<B>,
        action: Self::Action<B>,
        params: &Self::Params<B>,
    ) -> Step<B, Self::State<B>, Self::Obs<B>> { /* ... */ }
}

The bounds elided above (/* ... */) require that a state on one backend is the same structure on the other (State<Native> and State<Trace>), which #[derive(Tree)] gives.

step_env returns a Transition { obs, state, reward, terminated }; step returns a Step with the fields obs, state, reward, terminated, truncated, final_observation, and discount (gymnax's (obs, state, reward, terminated, truncated, info)).

For a complete example, see CartPole in the Quickstart or any environment in crates/ruxla-env/src/.

State, parameters, observations

  • State and parameters are #[derive(Tree)] structs of scalars and arrays. Writing the fields in the order of the original EnvState leaves (for ports) keeps the exported pytree identical.
  • Parameters are a pytree, so they can be batched in JAX (vmap over parameters). Configuration that changes shapes (a grid size, the number of agents) belongs in the environment struct instead, as a plain Rust field: shapes are fixed when tracing.
  • Observations can be an array (Array<B, f32>) or a struct of several fields. For VecEnv and the Python VecEnv, a multi-field observation is flattened into one f32 vector with the flat_obs! macro, which implements FlatObs:
use ruxla_core::{Array, Backend, I32, Native, Tree};
use ruxla_env::FlatObs;

#[derive(Clone, Tree)]
struct Obs<B: Backend> {
    grid: Array<B, f32>,
    steps: I32<B>,
}
ruxla_env::flat_obs!(Obs { grid, steps });

let obs = Obs::<Native> { grid: Array::from_slice(&[1.0, 2.0], [2]), steps: I32::new(7) };
let mut out = [0.0; 3];
obs.write_f32(&mut out);
assert_eq!((obs.shape(), out), (vec![3], [1.0, 2.0, 7.0]));

Note

The expansion of flat_obs! names the crate ruxla_core, so the crate that uses it needs ruxla-core (and ruxla-env) as direct dependencies, not only the facade ruxla.

Action spaces

action_space() returns an ActionSpace (gymnax's action_space):

ActionSpace Action<B> Notes
Discrete(n) I32<B> Actions 0..n
MultiDiscrete(nvec) Array<B, i32> of shape [nvec.len()] Component k in 0..nvec[k] (Jumanji's MultiDiscreteArray)
Box { low, high, shape } Array<B, f32> of shape One bound per element; ActionSpace::uniform_box(low, high, &shape) builds a box with the same bounds everywhere

num_actions() is the number of discrete actions (0 for a box). num_joint_actions() is the product of nvec for multi-discrete actions: joint actions are numbered in C order (unravel_joint converts an index into components).

Board games (such as TicTacToe) and many Jumanji environments have legal actions. legal_action_mask(state) returns a mask over the joint actions (Some(mask) with num_joint_actions() elements), or None if every action is legal (the default).

  • Environments with more joint actions than MAX_MASK_ACTIONS (2^20), such as Jumanji's JobShop (21^10), have no mask: ActionSpace::mask_len() is 0, and VecEnv, the compiled environments, and Python allocate no mask buffer.
  • Tests and benchmarks choose legal actions with choose_legal(mask, i), which picks the pattern_discrete(i, number of legal actions)-th legal action; the original JAX libraries are driven with the same rule when comparing.

Automatic reset

The provided step does what gymnax's step does: it splits the key in two, computes step_env and reset, and selects the reset state and observation where the episode ended (terminated or truncated). discount is 0 when the step reached a terminal state, 1 otherwise, and final_observation is the observation reached before any reset.

Natively, the reset is computed only when the episode ends (lax::select_with); the results are the same, and the traced IR keeps gymnax's select form.

step_env_uses_key() (default true): a deterministic environment returns false, so that natively step splits the key only when the reset needs it. Traced, the key is always split.

An environment can override step when the original does something else at a reset (for example, an environment that carries counters across episodes).

Writing for every backend

  • Data-dependent branches go through lax::cond, lax::switch, lax::select, or lax::select_with (see Control flow); loops through lax::fori_loop, lax::while_loop, or lax::scan.
  • Values that the original JAX code computes and then discards (a reset, random numbers used only on some branch) can be computed lazily natively with lax::select_with, keeping the IR identical.
  • B::FAST_PATHS is true natively; code can use it to take a native-only shortcut when the result is provably the same, without changing the traced IR.

Loops under JAX's vmap

When an environment is exported to JAX and batched with jax.vmap, a cond whose predicate differs between environments computes both branches for every environment, and a while_loop runs until every environment's loop has finished. A loop that terminates for every reachable state can still run forever on a lane whose branch is not taken (with a state the branch would never see). Bound such loops and make them stop when their branch is not selected. See the FAQ.

Testing an environment

ruxla::env::testing has the tools the repository uses:

  • check_backends(&env, steps, seed, xla) runs the same keys and actions natively, with the IR interpreter, and optionally with XLA (Xla::Run, needs a PJRT plugin; Xla::Skip otherwise), step by step, comparing integers and booleans exactly and floats within a tolerance;
  • check_vmap(&env, n, steps, xla) checks that the batched IR agrees with a loop over examples.
use ruxla::env::CartPole;
use ruxla::env::testing::{Xla, check_backends};

check_backends(&CartPole, 200, 0, Xla::Skip).unwrap();

For ports of JAX environments, the repository also compares with the original library step by step (reference data written by python/tools/gen_gymnax_testvectors.py and gen_pgx_testvectors.py, Python tests in python/tests/).