Native execution and VecEnv¶
With B = Native, an environment is ordinary Rust: env.reset(key, ¶ms) and
env.step(key, &state, action, ¶ms) compute their results immediately, with real branches and loops,
no XLA, and no Python.
use ruxla::prelude::*;
use ruxla::env::{CartPole, Environment};
let env = CartPole;
let params = env.default_params::<Native>();
let (obs, state) = env.reset(random::key(0), ¶ms);
let step = env.step(random::key(1), &state, I32::new(1), ¶ms);
assert_eq!(obs.shape().to_vec(), [4]);
The eager Native backend is convenient for tests, debugging, and code that needs no build step. It
pays a fixed cost per array operation (shape checks, small allocations), so for the fastest native
environments, compile the same code ahead of time.
VecEnv¶
VecEnv runs a batch of native environments in parallel on CPU threads and resets them automatically
(Environment::step):
use ruxla::env::{CartPole, VecEnv};
let mut envs = VecEnv::new(CartPole, 8, 0); // (environment, num_envs, seed)
let step = envs.step(&[1; 8]);
assert_eq!(step.reward, [1.0; 8]);
assert_eq!(envs.obs_f32().len(), 8 * 4);
- Keys. Environment
istarts fromfold_in(key(seed), i), splits it into its own key and the key of its first reset, and splits its key at every step (key, step_key = split(key), as PureJaxRL does). The same seed and actions therefore give the same trajectories as gymnax driven with these keys. - Results.
step(&actions)returns a&VecStepwithobs,reward,terminated,truncated, andfinal_obs(the observations before any reset, gymnax'sfinal_observation), one entry per environment, kept until the next step. - Resetting.
reset(Some(seed))starts over asnewwith that seed;reset(None)makes each environment split its current key and start a new episode. - Parameters.
VecEnv::with_params(env, params, num_envs, seed)uses non-default parameters. - Threads. A dedicated worker pool steps contiguous chunks of environments; workers spin briefly
between steps, so a step costs little more than its computation. By default the pool uses one
thread per physical core, and at most one per 32 environments;
set_num_threads(n)changes it (the calling thread included),num_threads()reads it.
Physical cores
The second hardware thread of a core shares its execution units and slows down spinning workers, which is why the default stops at the number of physical cores. Raising the thread count to every logical CPU is rarely faster.
Writing into your own buffers¶
step_into(&actions, StepBuffers { .. }) writes the flat f32 observations (FlatObs), rewards,
terminations, truncations, and final observations into contiguous buffers that you own. Each worker
writes the results of its own environments, so the copy is parallel too. Rust training loops and the
Python ruxla.VecEnv use this path; from Python, VecEnv.step_into writes into arrays you own, such as
pinned PyTorch tensors (Using ruxla from PyTorch).
use ruxla::env::{CartPole, StepBuffers, VecEnv};
let n = 8;
let mut envs = VecEnv::new(CartPole, n, 0);
let len = envs.obs_len();
let (mut obs, mut final_obs) = (vec![0.0; n * len], vec![0.0; n * len]);
let (mut reward, mut terminated, mut truncated) = (vec![0.0; n], vec![false; n], vec![false; n]);
envs.step_into(
&vec![1; n],
StepBuffers {
obs: &mut obs,
reward: &mut reward,
terminated: &mut terminated,
truncated: &mut truncated,
final_obs: &mut final_obs,
},
);
Other action types and masks¶
step(&[i32])is the shortcut for discrete actions.step_actions(Actions::..)andstep_into_actions(Actions::.., buffers)take any action type:Actions::Discrete(&[i32]),Actions::MultiDiscrete { data, dim }, orActions::Continuous { data, dim }(flat buffers, environment after environment).legal_action_masks_into(&mut [bool])writes every environment's legal action mask (flattened) and returnsfalseif the environment has none.
CompiledVecEnv¶
CompiledVecEnv::new(env, num_envs, seed) is the same thing for an environment
compiled ahead of time (a CompiledEnv): the same keys and the same step_into, so the same
trajectories as a VecEnv of the original environment, with fixed-size arrays and in-place steps.
use ruxla::env::CompiledVecEnv;
let mut envs = CompiledVecEnv::new(ruxla_env_aot::cartpole::Env, 8, 0);
let len = envs.obs_len();
// ... then `envs.step_into(&actions, StepBuffers { .. })` as above.
step_into_without_final(actions, obs, reward, terminated, truncated) steps without the final
observations: the generated code then skips computing the observation reached before an automatic
reset, which saves time when observations are large (Craftax has 8,268 floats per environment). The
next observations, rewards, and end flags are the same as those of step_into_actions.
Stack size
Compiled environments keep their arrays on the stack. The workers of VecEnv and
CompiledVecEnv have a 32 MiB stack; a large compiled environment (several MiB of state, as some
board games imported from Pgx have) can overflow the default 2 MiB stack of a thread you create
yourself.
Measuring¶
The example run of ruxla-env-jax steps a CompiledVecEnv of an imported environment on all cores
and prints the steps per second (Importing JAX environments):
See Benchmarks for measured results.