Skip to content

Developer guide

This page describes how ruxla is built inside, for contributors. The commands to build, test, and format the code, and the rules for commits, are in CONTRIBUTING.md. For the user-facing overview, see How ruxla works.

Layers

The crates form layers; each depends only on the layers below it.

ruxla-kernels                      operation semantics on typed slices (no dependencies)
   │
ruxla-ir                           IR, abstract values, Primitive trait, rule interfaces
   │
ruxla-prims                        the 128 primitives and their rules
   │
   ├── ruxla-interp                IR interpreter
   ├── ruxla-transforms            vmap, jvp, partial evaluation, transpose, vjp
   ├── ruxla-stablehlo             lowering to StableHLO
   ├── ruxla-pjrt                  PJRT bindings and execution
   ├── ruxla-codegen               IR optimization and Rust code generation
   └── ruxla-import                jaxpr (JSON) to IR
   │
ruxla-core (+ ruxla-macros)        frontend: backends, values, jnp, lax, random, jit, vmap, grad
   │
ruxla-env, ruxla-nn                environments, VecEnv, packages; layers and optimizers
   │
ruxla (facade), ruxla-env-aot, ruxla-env-jax, ruxla-python (+ python/ruxla)

ruxla-testing sits beside ruxla-core and is used only by tests.

Crate Responsibility
ruxla-kernels What every operation computes, on slices: elementwise operations, reductions, dot, gather, scatter, sorting, linear algebra, FFT, special functions. Follows XLA's CPU behavior where StableHLO leaves it to the implementation (integer division by zero, float-to-int conversion)
ruxla-ir Function, Eqn, Var, Atom, AVal, DType, Params, HostArray; the Primitive trait; the interfaces for batching (BatchCx), differentiation (AdCx), and lowering (LowerCx); printing in jaxpr format; binary serialization (RXIR)
ruxla-prims Each primitive's shape inference, evaluation, lowering, batching, JVP, and transpose rules; ruxla_prims::all() and by_name
ruxla-interp Evaluates a Function equation by equation with each primitive's eval
ruxla-transforms The drivers that walk a function and apply the primitives' rules
ruxla-stablehlo Turns a Function into a StableHLO module (MLIR text); links modules exported from JAX
ruxla-pjrt Loads PJRT plugins, compiles StableHLO, runs executables; FFI handlers for linear algebra and host callbacks
ruxla-codegen Optimizes IR (opt) and emits Rust (emit); rt is the runtime the generated code calls
ruxla-import Reads the JSON documents written by ruxla.export_jaxpr into a Function
ruxla-core The user-facing frontend, generic over Backend
ruxla-env Environment, VecEnv, CompiledVecEnv, .ruxlapkg export, compiled (generation of CompiledEnv modules), jax_env (loading exports), the reference environments
ruxla-nn Flax-compatible layers, Optax-compatible optimizers, weight loading, ExportedModel
ruxla-python The PyO3 module ruxla._ruxla: rules of ruxla_call for JAX, and the native VecEnv

Two backends

User code is generic over B: Backend. The two implementations share one source but do very different things:

  • Native runs eagerly. Values hold their data (NativeArray stores up to 8 elements inline, so that scalar-heavy environment code does not allocate per operation); each operation calls ruxla-kernels directly. Control flow functions (lax::cond, lax::while_loop, ...) run the chosen branch or the loop as ordinary Rust. B::FAST_PATHS is true, which lets code such as the automatic reset compute work lazily (lax::select_with) with the same results.
  • Trace records. Values are small Copy handles into a thread-local stack of trace frames; each operation appends an equation to the current frame. Nested functions (branches of cond, bodies of while and scan, jit) push frames of their own and capture outer values as extra inputs. The result is a ruxla_ir::Function, which make_ir returns and every other path consumes.

Values are typed (F32<B>, Array<B, T>, Bool<B>), so code that would work natively but cannot be traced (an if on a traced value) does not compile. Because both backends ultimately use the same kernels (natively directly, traced through the interpreter's eval), they agree bit for bit.

Everything after tracing is IR-to-IR or IR-to-something:

Path Implementation
vmap, jvp, vjp, grad ruxla-transforms, applying each primitive's rules
Interpretation ruxla-interp
jit on XLA ruxla-stablehlo then ruxla-pjrt
Inside JAX the package's IR is called through the JAX primitive ruxla_call; its abstract evaluation, batching, JVP, transpose, and lowering are answered by the Rust transformations through ruxla-python
Ahead-of-time compilation ruxla-codegen

Defining a primitive

A primitive implements ruxla_ir::Primitive:

Method Purpose
name The name, as in JAX (add, reduce_sum, scatter)
abstract_eval Output shapes and dtypes from input AVals and parameters; rejects invalid inputs
eval Evaluation on HostArrays, with ruxla-kernels
lower The StableHLO operations, through LowerCx
batch The batching rule (follows JAX's, so batched IR has the same form as JAX's)
jvp The forward-mode rule, emitting operations linear in the tangents
transpose For linear primitives, the cotangents of the linear inputs

Elementwise primitives are table entries keyed by the kernel operations (unary_prim, binary_prim, compare_prim) rather than separate types. To add a primitive:

  1. implement the kernel in ruxla-kernels;
  2. implement the rules in ruxla-prims and add the primitive to ruxla_prims::all();
  3. expose it in the frontend (ruxla-core's lax or jnp), and teach ruxla-import and python/ruxla/_jaxpr.py its JAX name and parameters if they differ;
  4. declare an OpInfo in ruxla-testing: samples of parameters and arguments for each element type. The tests fail for a primitive in all() without one;
  5. add an emitter in ruxla-codegen if generated code should not fall back to the interpreter for it.

Testing strategy

ruxla has three independent ways to run a program (the native backend, the interpreter, and XLA), plus JAX itself as the external reference. The tests compare them:

  • Native against interpreter, bit for bit. ruxla_testing::check_op evaluates every OpInfo sample with the interpreter and with the native backend's operations (ruxla_core::eval_native); they must agree exactly, since both use ruxla-kernels.
  • Interpreter against XLA, within tolerance. check_op_xla lowers each sample to StableHLO and runs it through a PJRT plugin, for every element type the primitive accepts. XLA is the independent implementation; these tests are #[ignore] because they need a plugin.
  • Batching. check_op_vmap compares each batched sample with a loop over examples.
  • Random programs. random_function builds well-typed programs from combinations of primitives to compare the three paths.
  • JAX reference data. JSON files under tests/data/ hold results computed with JAX (random numbers, jnp functions, linear algebra, FFT, layers, optimizers, environment trajectories). They are written by the scripts in python/tools/ (gen_*_testvectors.py, export_ppo_policy.py) and must stay reproducible with them.
  • Environments. ruxla_env::testing::check_backends runs an environment natively, on the interpreter, and optionally with XLA with the same keys and actions; crates/ruxla-env-aot/tests checks the generated code against Native bit for bit; crates/ruxla-env-jax/tests replays JAX's trajectories for imported environments; the Python tests (python/tests/) check the ports inside JAX against gymnax and Pgx.
  • Snapshots. The printed IR of representative programs is checked with insta (crates/ruxla-core/tests/snapshots/). When the printing changes, update them with INSTA_UPDATE=always cargo test and review the diff.

The code generator

ruxla_codegen::compile and ruxla_env::compiled::generate run two stages.

Optimization (ruxla_codegen::opt::optimize), every pass preserving values (checked against the interpreter), except the simplifications enabled by Options::fast_math:

  1. inline calls (jit, checkpoint, custom derivative rules);
  2. simplify: constant folding (including a cond with a constant index), algebraic simplification, common subexpression elimination, and dead code elimination, repeated after each later pass;
  3. sink broadcasts toward their uses;
  4. scalarize: split arrays of up to 8 elements into scalar operations, resolving data movement (broadcast_in_dim, slice, concatenate) at generation time;
  5. rewrite scatter chains into masked selects;
  6. turn selects on a scalar predicate into branches: work needed by only one side moves into a conditional, so that the automatic reset or a random draw used on one side runs only when needed;
  7. hoist outputs that every branch passes through unchanged.

Options::skip disables individual passes for debugging and ablation.

Emission (ruxla_codegen::emit): one-element values become Rust scalars and other arrays [T; N] (large ones on the heap); elementwise operations call the scalar kernels of ruxla-kernels, so results match the interpreter; 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. Operations without an emitter call the interpreter at run time and are marked with a comment.

ruxla_env::compiled wraps this for environments: it traces reset and step (with the automatic reset) and emits a module with State and Obs types and an Env implementing CompiledEnv. Generation runs in build scripts, as in crates/ruxla-env-aot/build.rs.

The import path

python/ruxla/_jaxpr.py      jax.make_jaxpr, then re-trace and rewrite into ruxla's primitives
        │                   (inline calls, threefry on raw u32 keys, lax rewrites, ...)
        ▼
JSON document               variables, base64 constants, equations with JAX's names and parameters
        │
ruxla-import                map names and parameters, insert implicit broadcasts, type-check
        ▼
ruxla_ir::Function          interpreter, codegen, or XLA, like traced IR

ruxla.export_env writes an environment's reset, step, and optional legal action mask as such documents plus a manifest.json; ruxla_env::jax_env::load_functions reads them, and ruxla_env::compiled::generate_from_functions generates a CompiledEnv from them. The ruxla-env-jax build script does this for every exported directory.

Design decisions worth knowing

  • JSON for import. The jaxpr is rewritten in Python, where JAX's own implementations (the PRNG, high-level primitives) are available, and handed to Rust as a self-describing JSON document. This avoids depending on JAX's internal serialization formats and keeps imports easy to inspect and diff. Packages exported from Rust to JAX use the compact binary RXIR format instead.
  • Parameters are folded into compiled environments. generate traces with the default parameters as constants, so that unused branches and random draws disappear. A different parameter set needs another generated module; the Native backend and the JAX export keep parameters as inputs.
  • gymnax-style automatic reset, lazy natively. Environment::step computes step_env and reset and selects, exactly as gymnax does, so traced IR and JAX exports match the originals. The native backend computes the reset only when an episode ends, and the code generator recovers the same laziness by turning the select into a branch.
  • JAX's names and semantics. Primitives, parameters, batching rules, and random numbers follow JAX 0.12, so IR traced from Rust has the form of a jaxpr, JAX exports compile to the same kind of HLO, and jaxprs can be imported without translation of meaning.
  • Static shapes. As in JAX, shapes are fixed at trace time. This is what lets the code generator use fixed-size arrays.