Transformations¶
Transformations take a closure over Trace values (a pytree of them) and return an object with
call methods. You write the program as a generic function and instantiate it with Trace inside the
closure:
use ruxla::prelude::*;
fn step<B: Backend>(x: Array<B, f32>, dt: F32<B>) -> Array<B, f32> {
&x + &(&x * dt)
}
let f = jit(|(x, dt): (Array<Trace, f32>, F32<Trace>)| step(x, dt));
- The input type is the closure's argument type
I;calltakes the same structure withNativevalues (I::On<Native>) and returns the output'sNativeversion. callruns with native values;call_tracedis used while tracing, to nest transformations (jit(vmap(grad(f)))): the inner transformation is called withcall_tracedinside the closure given to the outer one.
| Transformation | Called with native values | Called while tracing (call_traced) |
|---|---|---|
jit(f) |
Traces, compiles with XLA (cached), and runs | Becomes a jit equation in the outer IR |
vmap(f) |
Batches the IR and runs it on the interpreter (call) or XLA (call_xla) |
Inlines the batched IR |
grad, value_and_grad, vjp, jvp |
Differentiates the IR and runs it on the interpreter (call) or XLA (call_xla) |
Inlines the differentiated IR |
make_ir(f, &example) |
Returns the IR (like jax.make_jaxpr) |
|
interpret(f, &input) |
Traces and runs the IR with the interpreter |
jit¶
jit traces the closure once per input type, lowers the IR to StableHLO, compiles it with a PJRT
plugin (see XLA and PJRT), and caches the executable:
use ruxla::prelude::*;
let f = jit(|x: Array<Trace, f32>| jnp::sum(jnp::sin(&x), ALL));
let a = Array::from_vec(vec![1.0f32, 2.0], [2]);
let y = f.call(&a).to_scalar().value();
call panics if XLA fails; try_call returns a Result instead. Values are transferred between the
host and the device at each call. To keep values on the device (a training loop), put a pytree there
with device_put and use call_on_device:
// `Particle` is a `#[derive(Tree)]` struct and `step` a generic function
// (see crates/ruxla-core/tests/jit.rs).
let f = jit(|(p, dt): (Particle<Trace>, F32<Trace>)| (step(p, dt), dt));
let mut state = device_put(&(particle(), F32::new(0.1)));
for _ in 0..5 {
state = f.call_on_device(&state);
}
let (p, dt) = state.to_native();
call_on_device returns without waiting for the execution to finish (the device runs executions in
order, and to_native waits). call_on_device_donating(state) consumes its input and lets XLA reuse
its buffers for the result (JAX's donate_argnums); leaves shared with other OnDevice values are not
donated.
vmap¶
use ruxla::prelude::*;
let f = vmap(|(x, y): (F32<Trace>, F32<Trace>)| x * y + 1.0);
let out = f.call(&[(F32::new(2.0), F32::new(3.0)), (F32::new(4.0), F32::new(0.5))]);
assert_eq!(out.iter().map(|v| v.value()).collect::<Vec<_>>(), [7.0, 3.0]);
vmap traces the function once and batches the IR with each primitive's batching rule (the rules
follow JAX's), so the batched program has no loop. call takes a slice of examples and runs the batched
IR on the interpreter; call_xla runs it with XLA.
Many native examples
vmap does not turn native code into a loop. To run a generic program natively on many inputs,
call it in a loop (with B = Native, branches stay real), or use
VecEnv for environments.
Automatic differentiation¶
Differentiation is an IR transformation, ported rule by rule from JAX: forward mode (jvp), partial
evaluation, and transposition, with symbolic zeros, custom_jvp, custom_vjp, and checkpoint.
grad and value_and_grad take a closure of two arguments: the parameters to differentiate (a
pytree of floats) and the other arguments, which are not differentiated:
use ruxla::prelude::*;
use ruxla::value_and_grad;
type Params<B> = (Array<B, f64>, Array<B, f64>, Array<B, f64>, F64<B>);
/// The mean squared error of a two-layer network.
fn loss<B: Backend>(
(w1, b1, w2, b2): &Params<B>,
x: &Array<B, f64>,
y: &Array<B, f64>,
) -> Array<B, f64> {
let h = jnp::tanh(&(jnp::matmul(x, w1) + b1.clone()));
let pred = jnp::matmul(&h, w2) + *b2;
let d = pred - y.clone();
jnp::mean(&(d.clone() * d), ALL)
}
let f = value_and_grad(
|p: Params<Trace>, (x, y): (Array<Trace, f64>, Array<Trace, f64>)| loss(&p, &x, &y),
);
let (value, g) = f.call(¶ms, &(x, y)); // interpreter, natively
- The first leaf of the output is the loss (a float scalar); the other leaves are auxiliary outputs
returned without differentiation (JAX's
has_aux). callruns the differentiated IR on the interpreter (with the native kernels), so small models train without XLA;call_xlaruns it with XLA.- Values captured from an outer trace are not differentiated.
jvp and vjp take a one-argument closure:
use ruxla::{jvp, vjp};
let (out, tangent) = jvp(f).call(&primals, &tangents);
let (out, cotangent_of_inputs) = vjp(f).call(&primals, &cotangents);
Differentiation works through control flow: cond and scan in both modes, while in forward mode
only (as in JAX; use scan for reverse mode).
Custom rules and checkpointing¶
lax::custom_jvp(f, jvp, x), lax::custom_vjp(f, fwd, bwd, x), and lax::checkpoint(f, x) correspond
to JAX's custom_jvp, custom_vjp, and checkpoint. Natively they compute f; traced, they become the
primitives of the same names.
use ruxla::prelude::*;
/// `sin`, whose JVP rule deliberately gives `2 t`.
fn odd_sin<B: Backend>(x: Array<B, f64>) -> Array<B, f64> {
lax::custom_jvp(
|x: Array<B, f64>| jnp::sin(&x),
|x: Array<B, f64>, t: Array<B, f64>| (jnp::sin(&x), t * 2.0),
x,
)
}
/// d/dx x^3 computed as 3 r, with the residual r = x^2 from the forward pass.
fn cube<B: Backend>(x: F64<B>) -> F64<B> {
lax::custom_vjp(
|x: F64<B>| x * x * x,
|x: F64<B>| (x * x * x, x * x),
|r: F64<B>, g: F64<B>| g * r * 3.0,
x,
)
}
let g = ruxla::grad(|x: F64<Trace>, (): ()| cube(x)).call(&F64::new(2.0), &());
assert_eq!(g.value(), 12.0);
custom_jvp: the user's rule is used in forward mode; reverse mode linearizes it by partial evaluation and transposition.custom_vjp: reverse mode only (as in JAX).bwdcannot capture values of an outer trace; return them as residuals fromfwd.checkpoint: the backward pass recomputes the body instead of storing its intermediate values.- Values captured by the functions are not differentiated: pass what you differentiate as arguments.
Inspecting the IR¶
make_ir(f, &example) returns the IR (ruxla_ir::Function), whose Display follows the jaxpr format.
value_and_grad objects also have make_ir(¶ms, &args) (the differentiated IR), and
vmap objects make_ir(&example, n) (the batched IR for n examples).
interpret(f, &input) traces f and runs it with the interpreter, which is a convenient way to check
that a program gives the same results natively and as IR.