Skip to content

Ahead-of-time compilation

The eager Native backend checks shapes and allocates for each array operation, which dominates the step time of environments made of scalars and small arrays (typically 2 to 16 times slower than handwritten Rust). Calling XLA from Rust has a fixed cost of microseconds per call, too much for a step of tens of nanoseconds.

ruxla therefore compiles environments ahead of time to Rust: it traces the generic code, optimizes the IR, generates a Rust module of fixed-size arrays and scalars (ruxla-codegen), and lets rustc compile it together with the calling program. The result is about as fast as handwritten Rust and bit-identical to the Native backend.

What the code generator does

  • Optimization (ruxla_codegen::opt): inlining of calls (jit, checkpoint, custom rules), constant folding (including cond with a constant index), algebraic simplification, common subexpression elimination, and dead code elimination.
  • Selects become branches: when select_n operations share a scalar predicate, the work that only one side needs moves into a branch. The automatic reset (computed only when the episode ends) and random numbers used only on one side become real branches, as in handwritten code.
  • Small arrays become scalars: arrays of up to 8 elements are split into scalar operations, and data movement (broadcast_in_dim, slice, concatenate, ...) is resolved at generation time.
  • Emission (ruxla_codegen::emit): one-element values become Rust scalars, other arrays [T; N]; elementwise operations use the scalar kernels of ruxla-kernels (so the results match the interpreter bit for bit); cond, while, and scan become match, loop, and for; elementwise chains are fused into loops; arrays are updated in place when nothing else reads them; large arrays go to the heap.
  • Operations without a specialized emitter are evaluated by the interpreter at run time (correct but slow); the generated code marks them with a comment.

ruxla_codegen::compile(name, &function, &options) turns any IR function into a Rust function:

use ruxla_ir::{AVal, DType, Eqn, Function, Params, Var};

let x = Var::new(AVal::new([3], DType::F32));
let y = Var::new(AVal::new([3], DType::F32));
let f = Function {
    invars: vec![x.clone()],
    eqns: vec![Eqn {
        prim: ruxla_prims::MUL,
        inputs: vec![x.clone().into(), x.into()],
        params: Params::None,
        outputs: vec![y.clone()],
        loc: None,
    }],
    outvars: vec![y.into()],
    ..Function::default()
};
let code = ruxla_codegen::compile("square", &f, &Default::default()).unwrap();
assert!(code.contains("pub fn square(a0: &[f32; 3]) -> ([f32; 3],)"));

Options has fast_math (also use x * 0 = 0, x + 0 = x, which do not hold for NaN, infinities, or the sign of zero; off by default) and max_constant (the largest constant, in elements, that folding creates). skip turns individual passes off, which is useful when debugging the generator or measuring what a pass contributes; skipping a pass changes the generated code, not its results.

Compiled environments

ruxla_env::compiled::generate(&env, "module", &options) traces an environment's reset and step (with the automatic reset) with its default parameters as constants, optimizes them, and returns the source of a Rust module pub mod module { ... } with State and Obs types and a unit struct Env that implements CompiledEnv.

CompiledEnv has:

Method Description
reset(key) -> (Obs, State) A new episode
step(key, &state, action) -> CompiledStep One step with automatic reset (obs, state, reward, terminated, truncated, final_observation, discount)
step_in_place(key, &mut state, action, &mut obs) -> StepInfo The fast path: updates the state in place, writes the observation, skips the final observation
step_in_place_with_final(..) The same, also writing the final observation
legal_action_mask(&state, &mut [bool]) -> bool Writes the mask; false if the environment has none
obs_len, obs_shape, obs_into The observation as f32
state_leaves, obs_leaves, state_from_leaves Conversion to and from HostArray leaves (shared with the Native environment's pytrees)
name, action_space, num_actions As in Environment

Keys are the two u32 words of a JAX key: compiled::key(seed) and compiled::split_key(key) give the same values as random::key and random::split2. Actions are i32 (discrete), f32 (one element), [f32; N], or [i32; N] (multi-discrete).

use ruxla_env::compiled::{CompiledEnv, key, split_key};

let env = ruxla_env_aot::cartpole::Env;
let (_, mut state) = env.reset(key(0));
let mut k = key(1);
for t in 0..10 {
    let (next, sub) = split_key(k);
    k = next;
    state = env.step(sub, &state, t % 2).state;
}

Parameters are fixed

The parameters are folded into the generated code, so that unused branches and random numbers disappear. A different set of parameters needs another generated module.

Compiling your own environment

The generation runs in a build script, so the environment must live in a crate that the build script can depend on. crates/ruxla-env-aot is the template: copy its Cargo.toml, build.rs, and src/lib.rs, and replace the reference environments with yours. A typical layout:

my-env/            # the environment (Environment impl), depends on ruxla
my-env-compiled/   # build.rs generates the module; lib.rs includes it
my-env-compiled/Cargo.toml
[dependencies]
# The generated code refers to these crates.
ruxla-env = "0.1"
ruxla-codegen = "0.1"
ruxla-ir = "0.1"

[build-dependencies]
my-env = { path = "../my-env" }
ruxla-env = "0.1"
ruxla-codegen = "0.1"
my-env-compiled/build.rs
fn main() {
    let code = ruxla_env::compiled::generate(
        &my_env::MyEnv::default(),
        "my_env",
        &ruxla_codegen::Options::default(),
    )
    .expect("generate the compiled environment");
    let out = std::path::PathBuf::from(std::env::var("OUT_DIR").unwrap()).join("envs.rs");
    std::fs::write(out, code).unwrap();
    println!("cargo::rerun-if-changed=build.rs");
}
my-env-compiled/src/lib.rs
include!(concat!(env!("OUT_DIR"), "/envs.rs"));
// Now `my_env::Env` implements `ruxla_env::compiled::CompiledEnv`.

crates/ruxla-env-aot/build.rs does the same for several environments at once (one module each, written into one file) with fast_math, and its tests show how to check the generated code against Native. The generated module allows rustc and clippy warnings.

Build profile

Code generation is slow when the generator itself is unoptimized. The workspace optimizes build scripts and their dependencies in every profile:

[profile.dev.build-override]
opt-level = 3

[profile.release.build-override]
opt-level = 3

generate_from_functions(&EnvFunctions { .. }, "module", &options) does the same from IR functions that were not traced from an Environment, for example environments imported from JAX.

ruxla-env-aot

The crate ruxla-env-aot contains the five reference environments compiled ahead of time with their default parameters: the modules cartpole, acrobot, pendulum, breakout, and tic_tac_toe, each with a unit struct Env that implements CompiledEnv. Its build script calls ruxla_env::compiled::generate for each with Options { fast_math: true, .. }.

It is a default member of the workspace, so cargo test builds and tests it: tests/agree.rs checks that the compiled environments follow the Native ones bit for bit, and tests/vec_env.rs checks CompiledVecEnv against VecEnv.

Limits

  • Programs that use pure_callback (a host_callback) cannot be compiled (the generated crate cannot refer to a Rust closure).
  • The tested agreement is bit-for-bit with Native for the reference environments, with fast_math (crates/ruxla-env-aot/tests/agree.rs).
  • Compile times grow with the size of the environment: small environments generate and compile in about a second, large environments imported from JAX take tens of seconds or more of rustc time (see Benchmarks).