Python API¶
The Python package ruxla (source in python/ruxla/). Everything listed here is exported from
ruxla/__init__.py, plus the module ruxla.gymnasium.
import ruxla imports only VecEnv eagerly; the names that use JAX (Environment, load_env, load,
Package, Function, export_model, export_jaxpr, export_env, ruxla_call_p) are imported on
first access, so ruxla.VecEnv works without importing JAX.
Loading ruxla packages (JAX)¶
load_env¶
Loads an environment package written by ruxla_env::export (Rust). Raises ValueError if the package
is not of kind env or has an unsupported schema version.
import jax, ruxla
env = ruxla.load_env("cartpole.ruxlapkg")
obs, state = env.reset(jax.random.key(0))
obs, state, reward, terminated, truncated, info = env.step(jax.random.key(1), state, 1)
Environment¶
An environment loaded from a package of kind env, with gymnax 1.0's interface. Keys may be typed
(jax.random.key) or raw uint32[2] key data. All methods work under jax.jit, jax.vmap,
jax.lax.scan, jax.pmap, and jax.shard_map, and can be differentiated.
| Member | Description |
|---|---|
name |
The environment's name, such as "CartPole-v1" |
num_actions |
The number of discrete actions |
action_space |
{"type": "discrete", "n": n}, {"type": "box", "low": ..., "high": ..., "shape": ...}, or {"type": "multi_discrete", "nvec": ...} (from the manifest) |
obs_shape |
The shape of an observation (tuple) |
default_params |
Property: the default parameters (a pytree of frozen dataclasses) |
reset(key, params=None) |
Returns (obs, state); params defaults to default_params |
step(key, state, action, params=None) |
Returns (obs, state, reward, terminated, truncated, info) with automatic reset; info has "discount", "terminated", "truncated", and "final_observation" |
legal_action_mask(state) |
The legal action mask (bool[num_actions]), or None if the package has none |
package |
The underlying Package |
Actions are converted to int32 (discrete; reshaped to [len(nvec)] for multi-discrete) or to
float32 of the box's shape.
load¶
Loads any .ruxlapkg package (for example one written by Rust's PackageWriter).
Package¶
A loaded .ruxlapkg package: a directory with a manifest.json and one .ruxlair file per function.
| Member | Description |
|---|---|
Package(path) |
Loads the package; raises ValueError for an unsupported schema version |
path |
The package directory (Path) |
manifest |
The parsed manifest.json (dict) |
functions |
dict[str, Function] |
package[name] |
The function name |
Function¶
A function of a package, called with and returning pytrees. Calling it flattens the arguments into
leaves (raising TypeError if their number does not match the function's inputs), calls the primitive
ruxla_call, and rebuilds the output pytree (Rust structs become frozen dataclasses registered as
pytrees; keys travel as raw uint32[..., 2] data).
package = ruxla.load("functions.ruxlapkg")
f = package["mixed"]
a, b, c, d = f(x, y, n)
g = jax.grad(lambda x: jnp.sum(f(x, y, n)[0]))(x)
| Member | Description |
|---|---|
name |
The function's name in the package |
__call__(*args) |
Calls the function |
ruxla_call_p¶
The JAX primitive (jax.extend.core.Primitive("ruxla_call"), with multiple results) that calls ruxla
functions. Its abstract evaluation, batching, JVP, transpose, and lowering rules are delegated to ruxla
(see ruxla environments in JAX). You normally use it
through Function and Environment.
Exporting from JAX¶
export_model¶
Writes fn(params, *args) and its parameters for Rust (ruxla_nn::ExportedModel). example_args give
the shapes and types of the other arguments (arrays or jax.ShapeDtypeStruct). Returns the directory,
which contains:
weights.safetensors: the parameters, named by their path in the tree (params/Dense_0/kernel);model.mlir: the function exported withjax.export, taking the parameters (in the order of the tree's leaves) and then the other arguments;model_vjp.mlir: the VJP of the exported function, if JAX can differentiate it;manifest.json: the order of the parameters and the function's types.
Raises ValueError if the parameter tree has repeated paths. Needs the safetensors package.
ruxla.export_model(
network.apply, params, jax.ShapeDtypeStruct((4,), jnp.float32), path="ppo_cartpole_model"
)
export_jaxpr¶
Traces fn(*args) with jax.make_jaxpr, rewrites the jaxpr into the primitives that ruxla's IR has, and
returns the JSON document that Rust's ruxla_import::from_json reads. The inputs and outputs are the
leaves of the argument and result pytrees, in order; typed keys are their raw data.
See Importing JAX environments for the rewriting.
export_env¶
Writes an environment written in JAX to the directory path for ruxla to import
(ruxla_env::jax_env::load_functions) and compile ahead of time
(ruxla_env::compiled::generate_from_functions).
reset(key) -> (obs, state)andstep(key, state, action) -> (obs, state, reward, terminated, truncated, final_obs, discount)(the step with the automatic reset) work on pytrees; the parameters must be constants of the functions.legal_action_mask(state)gives the legal joint actions, if any.key(a rawuint32[2]key) andactionare examples.action_spaceis{"kind": "discrete", "n": n},{"kind": "multi_discrete", "nvec": [...]}, or{"kind": "box", "low": [...], "high": [...], "shape": [...]}.
Writes manifest.json, reset.json, step.json, and legal_action_mask.json (if given), and returns
the tree structures of the observation and the state.
ruxla.export¶
ruxla.export.export_envs(envs=None, out=".cache/jax-envs", steps=40, rollout_steps=1000, verbose=True)
Wraps environments of gymnax, Pgx, and Jumanji (and on request Craftax, Brax, MuJoCo Playground, NAVIX,
XLand-MiniGrid, JaxMARL, and Waymax) named library:name and exports them with export_env, with a
trajectory recorded by JAX; returns the exported directories. python -m ruxla.export is its command
line. Spec and export_one export environments of other libraries. See
Importing JAX environments.
compile_env¶
Compiles exported environments (directories, or library:name to export first) to a native shared
library with cargo and loads it. CompiledEnvs.modules lists the environments and
CompiledEnvs.vec_env(name, num_envs, seed=0, num_threads=None) makes a VecEnv. Needs a Rust
toolchain; see Compiling from Python.
Native vector environments (NumPy)¶
VecEnv¶
ruxla.VecEnv(name: str, num_envs: int, seed: int = 0, num_threads: int | None = None,
compiled: bool = True, library: CompiledEnvs | str | None = None)
With library (from compile_env, or the path of its shared library), name is one of the library's
modules.
num_envs copies of a native environment, stepped in parallel on CPU threads, with NumPy arrays and
without JAX.
| Argument | Description |
|---|---|
name |
One of ruxla._vec_env.ENV_NAMES ("CartPole-v1", "Acrobot-v1", "Pendulum-v1", "Breakout-MinAtar", "tic_tac_toe") or their lowercase aliases (cartpole, acrobot, pendulum, breakout); with an extension built with the feature jax-envs, also the module name of an imported environment, such as "gymnax_cartpole_v1" |
num_envs |
The number of environments |
seed |
The seed of the keys: environment i starts from fold_in(key(seed), i) |
num_threads |
The threads that step the environments (the calling thread included); defaults to the number of available cores, see Python VecEnv |
compiled |
Run the environments compiled ahead of time (default, much faster), or with the native backend; both give the same results |
| Member | Description |
|---|---|
reset(seed=None) -> np.ndarray |
Starts new episodes and returns float32[num_envs, *obs_shape]. With a seed, the environments start over as if created with it. Without one, the first call after creation returns the initial observations, later calls start new episodes from each environment's key |
step(actions) |
Steps every environment and resets the episodes that end. Returns (obs, reward, terminated, truncated, info): obs float32[num_envs, *obs_shape], reward float32[num_envs], terminated and truncated bool[num_envs], info["final_observation"] (the observations before any reset) |
step_into(actions, obs, reward, terminated, truncated) -> None |
Steps as step does, writing into arrays the caller allocated once: C-contiguous obs (float32, num_envs * prod(obs_shape) elements), reward (float32[num_envs]), terminated and truncated (bool[num_envs]). Allocates nothing per step and does not compute the final observations (those before an automatic reset) |
legal_action_mask() |
bool[num_envs, num_joint_actions], or None if the environment has none |
name |
The environment's name |
num_envs |
The number of environments |
num_actions |
The number of discrete actions (0 for continuous actions) |
action_space |
("discrete", n), ("multi_discrete", nvec), or ("box", low, high, shape) |
continuous |
Whether the actions are continuous |
obs_shape |
The shape of one environment's observation |
obs_dtype |
float32 |
action_dtype |
int32, or float32 for continuous actions |
num_threads |
The number of threads (settable) |
actions are integers (one per environment), int32[num_envs, len(nvec)] for multi-discrete actions,
or float32[num_envs, *shape] for continuous ones.
import numpy as np, 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 Using ruxla from PyTorch for a training loop that steps a VecEnv with
step_into into pinned PyTorch tensors.
ruxla.gymnasium¶
VectorEnv¶
ruxla.VecEnv as a Gymnasium 1.x vector environment (gymnasium.vector.VectorEnv), with
metadata = {"autoreset_mode": AutoresetMode.SAME_STEP}. Requires gymnasium.
| Member | Description |
|---|---|
reset(*, seed=None, options=None) |
Returns (obs, {}); seed must be an integer or None (one seed for all environments; environment i starts from fold_in(key(seed), i)), options is ignored |
step(actions) |
Returns (obs, reward, terminated, truncated, infos); where episodes ended, infos["final_obs"] (object array) holds their last observations and infos["_final_obs"] marks them |
single_observation_space, observation_space |
Box spaces (bounds from gymnax where known) |
single_action_space, action_space |
Discrete, MultiDiscrete, or Box |
envs |
The underlying ruxla.VecEnv |