Skip to content

Training in Rust

ruxla is meant to be used with JAX's training ecosystem, but models can also be defined and trained in Rust alone, with ruxla::nn (crate ruxla-nn): Flax-compatible layers, initializers, and optimizers that compute what Optax computes.

Layers and initializers

Item Follows
Dense flax.linen.Dense
Conv flax.linen.Conv (HWIO kernels, SAME/VALID/explicit padding, strides, input and kernel dilation, feature_group_count)
LayerNorm flax.linen.LayerNorm (epsilon, use_fast_variance)
max_pool, min_pool, avg_pool flax.linen pooling (avg_pool with count_include_pad)
relu, tanh Activations
init::orthogonal, init::zeros jax.nn.initializers (computed natively, once)

Layers are generic over the backend (Dense<B>), so a model is a #[derive(Tree)] struct that runs natively, under jit, and under grad. Their outputs and gradients match Flax and jax.grad within 2e-5 natively, on the interpreter, and with XLA (python/tools/gen_nn_testvectors.py writes the reference data).

Optimizers

ruxla_nn::optim follows Optax 0.2: gradient transformations that are chained, applied to the gradient, and added to the parameters. They are generic over the backend, so a training step runs natively or is traced and compiled inside jit.

Function or type Optax
sgd(learning_rate) optax.sgd (without momentum)
adam(learning_rate), adam_with_schedule(schedule) optax.adam
ScaleByAdam { b1, b2, eps, eps_root } optax.scale_by_adam
clip_by_global_norm(max_norm) / ClipByGlobalNorm optax.clip_by_global_norm
linear_schedule(init, end, transition_steps) optax.linear_schedule
chain(a, b) / Chain(a, b) optax.chain
ScaleBySchedule(schedule), Scale(factor) optax.scale_by_schedule, optax.scale
apply_updates optax.apply_updates
use ruxla_core::{Array, Native};
use ruxla_nn::optim::{GradientTransformation, adam, apply_updates};

let params = (Array::<Native, f32>::from_vec(vec![1.0, 2.0], [2]),);
let opt = adam(0.1);
let state = opt.init_tree::<Native, f32, _>(&params);
let grads = (Array::<Native, f32>::from_vec(vec![0.5, -0.5], [2]),);
let (updates, _state) = opt.update_tree(&grads, state);
let params = apply_updates::<Native, f32, _>(&params, &updates);
// The first step of Adam moves each parameter by about the learning rate;
// the values are those of Optax.
assert_eq!(params.0.to_vec(), [0.9000007, 2.0999994]);

With the same inputs, the optimizers give the same values as jitted Optax, bit for bit.

A training step

A step combines value_and_grad with an optimizer. Inside a traced program (here, the minibatch update of the PPO example), the gradient is computed with call_traced:

let update_minibatch = |(params, opt_state): (ActorCritic<Trace>, OptState<Trace>),
                        mb: Batch<Trace>| {
    let ((total, _aux), grads) =
        value_and_grad(|p: ActorCritic<Trace>, mb: Batch<Trace>| loss(config, &p, &mb))
            .call_traced(params.clone(), mb);
    let (updates, opt_state) = tx.update_tree::<Trace, f32, _>(&grads, opt_state);
    ((apply_updates::<Trace, f32, _>(&params, &updates), opt_state), total)
};

Called with native values, value_and_grad(..).call(&params, &batch) runs the differentiated IR on the interpreter, which is enough for small models without XLA; jit compiles the whole step (or the whole training) with XLA for speed.

Example: PPO on CartPole

crates/ruxla-nn/examples/ppo_cartpole is a port of PureJaxRL's ppo.py written in Rust only. The whole training (rollouts of the environments batched with vmap, the advantages with lax::scan_reverse, and the minibatch updates with value_and_grad, gradient clipping, and Adam with a linear schedule) is one traced program, compiled once with jit. It prints the learning curve as JSON.

scripts/fetch-pjrt-plugins.sh   # the example runs with XLA
cargo run --release -p ruxla-nn --example ppo_cartpole -- --seed 0 --timesteps 500000 [--platform cuda]

Options: --seed, --timesteps, --num-envs, and --platform cpu|cuda.

How it compares

The test crates/ruxla-nn/tests/ppo_rust.rs (#[ignore], needs the PJRT CPU plugin) checks that the mean learning curve over 4 seeds stays within 15% of PureJaxRL's mean over 8 seeds (crates/ruxla-nn/tests/data/purejaxrl_cartpole.json, written by python/tools/gen_ppo_curves.py).