Python VecEnv and Gymnasium¶
ruxla.VecEnv runs native environments on CPU threads and exchanges NumPy arrays — a CPU vector
environment in the spirit of envpool. It does not use JAX or XLA, and import ruxla does not import
JAX.
import numpy as np
import ruxla
envs = ruxla.VecEnv("CartPole-v1", num_envs=256, seed=0)
obs = envs.reset() # float32[256, 4]
actions = np.random.randint(0, envs.num_actions, envs.num_envs)
obs, reward, terminated, truncated, info = envs.step(actions)
final_obs = info["final_observation"]
Semantics¶
- Environments.
ruxla.VecEnv(name, num_envs, seed=0, num_threads=None, compiled=True).nameis one of the reference environments (ruxla._vec_env.ENV_NAMES):CartPole-v1,Acrobot-v1,Pendulum-v1,Breakout-MinAtar, andtic_tac_toe, or the lowercase aliasescartpole,acrobot,pendulum, andbreakout. With the featurejax-envs, imported environments are available too (below). - Compiled or native. With
compiled=True(the default), the environments compiled ahead of time (ruxla-env-aot) run; withcompiled=False, theNativebackend runs the generic code. Both give the same results. - Keys. Environment
istarts fromfold_in(key(seed), i)(jax.randomwith threefry), splits it for its first reset, and splits its key at every step. The same seed and actions give the same trajectories as the RustVecEnvand as gymnax driven with these keys. - Automatic reset. Episodes that end are reset in the same step:
obsis the first observation of the next episode there, andinfo["final_observation"]holds the observations the step reached (equal toobswhere the episode goes on), like gymnax'sfinal_observation. - Arrays. Every call returns new arrays; the worker threads write into them directly, with the GIL
released. Observations are
float32[num_envs, *obs_shape](multi-field observations are flattened), rewardsfloat32[num_envs],terminatedandtruncatedbool[num_envs].
Stepping into your own arrays¶
step_into(actions, obs, reward, terminated, truncated) steps like step but writes the results into
arrays that you allocate once and reuse, so nothing is allocated per step:
n = envs.num_envs
obs = np.zeros((n, *envs.obs_shape), np.float32)
reward = np.zeros(n, np.float32)
terminated = np.zeros(n, np.bool_)
truncated = np.zeros(n, np.bool_)
envs.step_into(actions, obs, reward, terminated, truncated)
- The arrays must be C-contiguous and writable, with dtypes
float32(obs,reward) andbool(terminated,truncated);obsneedsnum_envs * prod(obs_shape)elements, the othersnum_envs. The NumPy views of PyTorch CPU tensors (tensor.numpy(), also of pinned tensors) qualify. - There are no final observations: where an episode ends,
obsholds the first observation of the next episode, and environments compiled ahead of time skip computing the observation that ended it. Usestepwhen you need it, for example to bootstrap the value of truncated episodes.
Actions¶
action_space |
Actions passed to step |
|---|---|
("discrete", n) |
integers in 0..n, one per environment |
("multi_discrete", nvec) |
int32[num_envs, len(nvec)] |
("box", low, high, shape) |
float32[num_envs, *shape] |
continuous tells whether the actions are a box, action_dtype is int32 or float32.
Legal action masks¶
Board games such as tic_tac_toe have legal actions. legal_action_mask() returns
bool[num_envs, num_joint_actions] (row-major over the components for multi-discrete actions), or None
if the environment has none.
envs = ruxla.VecEnv("tic_tac_toe", num_envs=16)
obs = envs.reset()
mask = envs.legal_action_mask() # bool[16, 9]
actions = np.array([np.flatnonzero(m)[0] for m in mask], np.int32)
obs, reward, terminated, truncated, info = envs.step(actions)
Threads¶
num_threads (constructor or property) is the number of threads that step the environments, the calling
thread included; by default, the Rust VecEnv's choice (one per physical core, at most one per 32
environments).
Timing from Python
NumPy loads OpenBLAS, whose threads can spin and take CPU time from ruxla's workers. Set
OPENBLAS_NUM_THREADS=1 when measuring. At small batch sizes, the fixed cost of a call (allocating
the result arrays, releasing the GIL) dominates.
Environments imported from JAX¶
Environments imported from JAX (Importing JAX environments) can be stepped the
same way, by their module names. With a Rust toolchain, ruxla.compile_env compiles them on the spot:
import numpy as np, ruxla
compiled = ruxla.compile_env("gymnax:Catch-bsuite")
envs = compiled.vec_env("gymnax_catch_bsuite", num_envs=1024, seed=0)
From a clone, they can also be built into the extension module with the feature jax-envs after
exporting them. The environments compiled into it are chosen at build time, like those of
ruxla-env-jax (RUXLA_JAX_ENVS_ONLY selects some of the exported ones):
JAX_PLATFORMS=cpu .venv/bin/python -m ruxla.export gymnax:Catch-bsuite
cd python && VIRTUAL_ENV=$PWD/../.venv ../.venv/bin/maturin develop --release --features jax-envs
import numpy as np, ruxla
envs = ruxla.VecEnv("gymnax_catch_bsuite", num_envs=1024, seed=0)
obs = envs.reset()
obs, reward, terminated, truncated, info = envs.step(np.zeros(1024, np.int32))
This is how a training loop keeps a JAX environment on the CPU as native code while the agent runs on the GPU.
Gymnasium¶
ruxla.gymnasium.VectorEnv wraps ruxla.VecEnv as a Gymnasium 1.x vector environment:
from ruxla.gymnasium import VectorEnv
envs = VectorEnv("CartPole-v1", num_envs=256)
obs, info = envs.reset(seed=0)
obs, reward, terminated, truncated, info = envs.step(envs.action_space.sample())
- The autoreset mode is
AutoresetMode.SAME_STEP: where an episode ends,obsis the first observation of the next episode,info["final_obs"](an object array) holds the last observation of the episode that ended, andinfo["_final_obs"]marks the environments that ended. - Seeds follow ruxla (environment
istarts fromfold_in(key(seed), i)), not Gymnasium'sseed + i;resettakes one integer seed for all environments and ignoresoptions. - The single observation space is a
Boxwith bounds taken from gymnax where known; the action space isDiscrete,MultiDiscrete, orBox.
Agreement¶
The Python tests check that ruxla.VecEnv follows the original libraries with the same keys and actions
(python/tests/test_vec_env.py against gymnax, test_pgx_envs.py against Pgx): integer environments
such as Breakout and tic-tac-toe agree exactly, and float environments such as CartPole agree up to the
last bits of floats.