Skip to content

Concepts

This page introduces the frontend of ruxla (ruxla-core, re-exported by ruxla): backends, values, operations, control flow, random keys, and pytrees. Most programs start with:

use ruxla::prelude::*;

The prelude brings Backend, Native, Trace, the value types (Scalar, Array, F32, F64, I32, I64, U8, U32, Bool, C64, C128, Key), the element traits, Tree, the modules jnp, lax, and random, ALL, and the transformations jit, vmap, and device_put. Other transformations (grad, value_and_grad, jvp, vjp, make_ir, interpret) are at the crate root (ruxla::grad, ...).

Backends

A program is Rust code generic over a backend B: Backend:

use ruxla::prelude::*;

fn energy<B: Backend>(x: &Array<B, f32>) -> F32<B> {
    jnp::sum(x.square(), ALL).to_scalar() * 0.5
}

let x = Array::<Native, f32>::from_vec(vec![1.0, 2.0], [2]);
assert_eq!(energy(&x).value(), 2.5);
Backend What running the code does
Native Computes the result immediately, as compiled Rust. Scalars are the numbers themselves, arrays own their buffers, branches and loops are real.
Trace Records the operations as IR (like jax.make_jaxpr). Traced values hold no data, only a reference to an IR variable.

The same function therefore runs natively, or becomes IR that ruxla transforms, runs on its interpreter, lowers to XLA, exports to JAX, or compiles back to Rust ahead of time. You usually do not name Trace yourself except in the closures you pass to transformations:

use ruxla::prelude::*;
use ruxla::make_ir;

let ir = make_ir(|x: F32<Trace>| (x * 2.0).sin(), &F32::new(1.0));
assert_eq!(
    ir.to_string(),
    "{ lambda ; a:f32[]. let\n    b:f32[] = mul a 2.0:f32[]\n    c:f32[] = sin b\n  in (c,) }"
);

The printed IR follows the jaxpr format, so it can be compared with JAX's jaxprs side by side.

Native fast paths

The Native backend has specialized implementations of some generic functions (random numbers, single-element updates, small sorts, ...), checked to give bit-identical results; the traced IR keeps the JAX form. For the fastest native code, compile the IR ahead of time.

Values

Type Meaning Copy
Scalar<B, T> A scalar of element type T yes
Array<B, T> An array; the shape is known at run time (and fixed per traced program) no (clone is cheap: the native buffer is shared)
Key<B> A random key (u32 data of shape [2], like JAX's threefry keys) no (clone is cheap)

Aliases: F32<B> = Scalar<B, f32>, and likewise F64, I32, I64, U8, U32, Bool, C64, C128.

Element types are bool, i8 to i64, u8 to u64, f16, bf16, f32, f64, and the complex types c64 and c128. Traits group them: Numeric (arithmetic), Num (real numbers: clamp, %), Inexact (floats and complex numbers: exp, ln, sqrt, sin, ...; the differentiable types), Float, ComplexFloat, and Int.

Some natively useful constructors and accessors:

let s = F32::<Native>::new(1.5);
assert_eq!(s.value(), 1.5);
let a = Array::<Native, f32>::from_vec(vec![1.0, 2.0, 3.0], [3]);
assert_eq!(a.to_vec(), [1.0, 2.0, 3.0]);

Operations

Names and semantics follow JAX (jax.numpy as jnp, jax.lax as lax):

Writing Example Notes
Arithmetic operators x * x + 2.0 * y, -x, a % b Literals take the value's element type
Comparisons x.lt(y), x.eq(0) Methods returning Bool<B> (Rust's < must return bool)
Logic a & b, a \| b, !a, a ^ b On Bool<B>
Math x.sin(), jnp::exp(&x), jnp::clip(..) Methods and jnp functions
Conversion x.cast::<f32>(), jnp::astype No implicit promotion
Construction jnp::zeros::<B, f32>([3, 4]), jnp::stack(&[x, y, z], 0), Array::from_vec(..)
Indexing a.i((y, x)), a.i((.., 0)), a.at((y, x)).set(1.0), jnp::take, jnp::roll(&a, 1, 0) Static and run-time (I32<B>) indices, ranges
Reductions jnp::sum(&a, ALL), jnp::max(&a, 0), jnp::argmax(&a, -1)
Sorting lax::sort(&x, 0), lax::sort_key_val(&k, &v, 0) Stable; JAX's total order for floats
Matrix products a.dot(&b), jnp::matmul(&a, &b)
Linear algebra, FFT jnp::linalg::solve, jnp::linalg::svd, jnp::fft::fft, lax::linalg::* Follow jnp.linalg, jnp.fft, lax.linalg

Broadcasting follows NumPy's rules in jnp and the operators; lax functions need matching shapes, as in JAX.

Correspondence with JAX

JAX ruxla
jnp.sin(x) jnp::sin(&x), x.sin()
x < y x.lt(y)
jnp.where(c, a, b) jnp::where_(c, a, b) (where is a Rust keyword)
lax.cond(p, f, g, x) lax::cond(p, f, g, x)
x.at[i].set(v) x.at(i).set(v)
x[1:3, 0] x.i((1..3, 0))
jax.random.uniform(key, (4,), minval=-1., maxval=1.) random::uniform(&key, [4], -1.0, 1.0)
untyped jnp.ndarray F32<B>, Array<B, f32>: element types are written, scalars and arrays differ
weak types and implicit promotion literal inference and explicit cast
@jax.jit jit(f)
flax.struct.dataclass #[derive(Tree)]

Updating arrays

x.at(i).set(v) returns a new array, like JAX. Natively, two variants avoid copies when the array is not shared:

  • x.into_at(i).set(v) consumes x;
  • x.at_mut(i).set(v) updates x in place (x = x.at[i].set(v) in JAX).

The traced IR is the same scatter in every case. The reference Breakout builds its observation this way:

let mut obs = jnp::zeros::<B, bool>([10, 10, 4]);
obs.at_mut((9i64, s.pos, 0i64)).set(true);
obs.at_mut((s.ball_y, s.ball_x, 1i64)).set(true);
obs.at_mut((s.last_y, s.last_x, 2i64)).set(true);
obs.at_mut((.., .., 3i64)).set(s.brick_map.cast::<bool>());

Control flow

Bool<B> is not bool, so an if on a value does not compile in generic code: code that "works natively but cannot become IR" cannot be written. Use the lax functions, which have JAX's names and semantics:

Function Native Trace
lax::select(pred, on_true, on_false) if (both operands are computed) select_n
lax::cond(pred, true_fn, false_fn, operand) if cond
lax::switch(index, &branches, operand) match (index clamped) cond with an index
lax::fori_loop(lo, hi, body, init) for scan if both bounds are static, while otherwise
lax::while_loop(cond_fn, body_fn, init) while while
lax::scan(f, init, xs, length) a loop scan (lax::scan_reverse from the end)

operand and init are pytrees. Plain Rust if and for are fine for conditions that do not depend on values (configuration, shapes, constants); tracing unrolls them.

use ruxla::prelude::*;

fn relu<B: Backend>(x: F32<B>) -> F32<B> {
    lax::cond(x.gt(0.0), |x| x, |_| F32::new(0.0), x)
}

fn collatz_steps<B: Backend>(n: I32<B>) -> I32<B> {
    let (_, steps) = lax::while_loop(
        |(n, _): &(I32<B>, I32<B>)| n.gt(1),
        |(n, s)| (lax::select((n % 2).eq(0), n / 2, n * 3 + 1), s + 1),
        (n, I32::new(0)),
    );
    steps
}
assert_eq!(collatz_steps::<Native>(I32::new(27)).value(), 111);

Two more functions let native code skip work that JAX computes and discards:

  • lax::select_with(pred, || a, || b): natively, only the chosen side runs; traced, both run and are selected (the same IR as lax.select in JAX). The closures must be pure.
  • lax::select_with_operand(pred, x, |x| a, |x| b): the same, with the chosen side receiving x by value, so that it can update arrays in place.
use ruxla::prelude::*;

let grid = Array::<Native, f32>::from_vec(vec![0.0; 4], [2, 2]);
let grid = lax::select_with_operand(
    Bool::<Native>::new(true),
    grid,
    |g| g.into_at((.., 0i64)).set(1.0f32),
    |g| g.into_at((.., 1i64)).set(1.0f32),
);
assert_eq!(grid.to_vec(), [1.0, 0.0, 1.0, 0.0]);

Random numbers

Keys are Key<B>; the functions follow jax.random and give the same bits as JAX (threefry2x32, computed natively or as the threefry2x32 primitive):

use ruxla::prelude::*;

let key = random::key::<Native>(0);
let (a, b) = random::split2(&key);
let k = random::fold_in(&key, 7u32);
let u = random::uniform(&a, [5], 0.0f32, 1.0f32);
let n = random::normal::<Native, f32>(&b, [2, 3]);
let i = random::randint(&k, [4], -3i32, 7i32);

Available functions include key, split, split2, fold_in, bits, uniform, batched_uniform, normal, randint, bernoulli, gumbel, categorical, permutation, shuffle, choice, choice_with_p, and the distributions exponential, laplace, logistic, cauchy, pareto, weibull_min, rademacher, maxwell, double_sided_maxwell, truncated_normal, gamma, loggamma, beta, dirichlet, t, chisquare, f, poisson, and binomial.

Note

Integer-only distributions match JAX bit for bit. Distributions that go through log, log1p, or erf (for example loggamma, dirichlet, truncated_normal) can differ in the last bits.

Pytrees

Structured inputs and outputs (states, parameters, carries of loops) are pytrees. Derive Tree for structs whose type parameter is the backend:

use ruxla::prelude::*;

#[derive(Clone, Debug, Tree)]
struct Particle<B: Backend> {
    x: Array<B, f32>,
    v: Array<B, f32>,
    steps: I32<B>,
    #[tree(static)]
    name: &'static str,
}

#[derive(Tree)] generates the flattening into leaves and back, a leaf-by-leaf select, the structure description (field names, used by the Python package), and the same type on another backend (Particle<Native> and Particle<Trace>). Fields marked #[tree(static)] are not leaves: they are copied unchanged (configuration). Tree is also implemented for scalars, arrays, keys, tuples, (), arrays [T; N], Vec<T>, and Option<T>.

Native-only code

Code that cannot be generic (calls into other libraries, arbitrary data structures) can be written for B = Native only. pure_callback(name, f, like, input) (JAX's pure_callback) calls such a native function from generic code: natively it calls f; traced, it becomes a host_callback equation that the interpreter and ruxla's XLA path can run. Programs that contain it cannot be saved to .ruxlapkg, embedded in JAX, or compiled ahead of time, and the call is not differentiable.

use ruxla::prelude::*;
use ruxla::{interpret, pure_callback};

fn sorted(x: Array<Native, f32>) -> Array<Native, f32> {
    let mut v = x.to_vec();
    v.sort_by(f32::total_cmp);
    Array::from_vec(v, [3])
}
let like = Array::<Native, f32>::from_vec(vec![0.0; 3], [3]);
let x = Array::<Native, f32>::from_vec(vec![3.0, 1.0, 2.0], [3]);
assert_eq!(pure_callback("sorted", sorted, &like, &x).to_vec(), [1.0, 2.0, 3.0]);
let out = interpret(
    |x: Array<Trace, f32>| pure_callback("sorted", sorted, &like, &x) * 2.0,
    &x,
);
assert_eq!(out.to_vec(), [2.0, 4.0, 6.0]);

Semantics

Where StableHLO leaves behavior to the implementation, ruxla follows XLA on the CPU, and the native backend and the interpreter share the same kernels (ruxla-kernels). For example, integer overflow wraps around, integer division by zero gives -1 (signed) or the maximum (unsigned), float-to-integer conversions saturate (NaN becomes 0), and out-of-bounds dynamic_slice/gather indices are clamped while out-of-bounds scatter updates are dropped.

use ruxla_kernels::{BinaryOp, Ops, cast};

assert_eq!(i32::binary(BinaryOp::Div, 7, 0), -1);
assert_eq!(cast::<f32, i32>(f32::NAN), 0);

Floats are rounded operation by operation. XLA fuses multiplications and additions into FMAs and uses its own transcendental functions, so native results and XLA (or JAX) results can differ in the last bits; integers, booleans, and random bits agree exactly.