Skip to content

Transforms

Jacobi compiles plain Rust closures into fused XLA programs. Every transform composes freely with the others.

Lazy Eager Fusion (sync and Tensor::eval)

Outside jit, eager operations automatically batch into a pending XLA graph and flush together as one fused XLA execution the moment you read a value (.item(), .to_host(), .to_vec_f32(), .save(), debug_print), pass a tensor into jit or pmap, or reach the batch threshold (default 128 IR nodes or 256 MiB pending bytes, configurable via JACOBI_LAZY_MAX_NODES and JACOBI_LAZY_MAX_BYTES). Varying Rust scalars such as learning-rate schedules are passed as dynamic scalar inputs so the fused graph reuses its cached executable without recompiling, and lazy flushes stay in the bounded in-memory LRU cache rather than writing to ~/.jacobi/cache.

For tight training loops that never read intermediate values, wrap the step in jit(...) or call sync() at the end of each step so flush boundaries align cleanly with your loop. You can also call tensor.eval()? whenever you want an explicit timing barrier.

Shape and dtype errors record caller source locations via #[track_caller], reporting the exact Rust file and line in both eager mode and inside jit.

Compilation (jit, call_async, eval, and eval_shape)

jit traces your function once per unique (engine, precision, autocast, shapes, dtypes) signature and caches the compiled executable in memory (bounded LRU, default 256 entries) and on disk (~/.jacobi/cache, bounded at 512 MiB by default). Matching uniquely-owned input and output buffers are donated in place via tf.aliasing_output automatically (toggle with .donate(false)).

let f = jit(|x: Tensor| (&x * 2.0 + 1.0).tanh().sum());
let out = f.call(Tensor::randn(&[1024]))?;

// Overlap host data loading with async device execution
let pending = f.call_async(Tensor::randn(&[1024]))?;
let out_async = pending.wait()?;

Pair call_async with DataLoader or Prefetcher::new(batch_iter, 2) to load and preprocess the next host batch on a background thread while the accelerator runs the current step.

For one-off computations, eval compiles and runs a closure right away. To inspect output shapes and dtypes without allocating buffers or compiling XLA executables, call eval_shape. To pre-compile and cache an executable ahead of time without allocating device memory, pass Tensor::spec(&shape, dtype) placeholders to JitFn::compile_for.

let out = eval(|| model.forward(&x))?;
let specs = eval_shape(&x, |t| model.forward(&t))?; // Vec<TensorSpec>
let _mlir = f.compile_for(&Tensor::spec(&[1024], Dtype::F32))?;

For multi-device data parallelism (pmap), SPMD sharding (Mesh, NamedSharding, shard_map), and multi-node hybrid DP x EP training, see Distributed Training.

Reverse-Mode Autodiff (grad, value_and_grad, jacobian)

Compute gradients with respect to a Tensor, a tuple, or any #[module] struct.

let (loss, grads) = value_and_grad(|m| m.loss(&x, &y), &model);

Higher-order derivatives work naturally by nesting grad.

let x = Tensor::scalar(2.5);
let d2 = grad(|t| grad(|u| &u * &u * &u, &t), &x); // 15.0

Call x.detach() anywhere to stop gradients from flowing through a tensor. For 1D vector functions, jacobian(|x| f(x), &x) returns the full reverse-mode Jacobian matrix.

Memory-Efficient Low-Rank Gradients (efficient_grad, value_and_efficient_grad)

Compress 2D and batched 3D/4D parameter gradients into orthonormal low-rank factors left @ right (EfficientGrad<P>) via randomized subspace iteration and Newton-Schulz orthogonalization. Pair with EfficientAdamW to keep both gradients and optimizer moments in low-rank space (value_and_efficient_grad, efficient_grad, value_and_efficient_grad_with, value_and_efficient_grad_warm).

let (loss, eff_grads) = value_and_efficient_grad(|m| m.loss(&x, &y), &model, 32);
println!("compression {:.1}x", eff_grads.compression_ratio());

Forward-Mode Autodiff (jvp, jacfwd, and hvp)

Use jvp to compute a Jacobian-vector product in a single forward pass across any #[module] input and output. jacfwd computes full forward-mode Jacobians (ideal when output dimension exceeds input dimension), and hvp computes Hessian-vector products via forward-over-reverse autodiff in constant passes regardless of parameter count.

let (y, dy) = jvp(|t: Tensor| (&t * &t).sin(), &x, &tangent);
let jac = jacfwd(|t: Tensor| model.forward(&t), &x);
let hv = hvp(|p: MyNet| p.loss(&x, &y), &model, &tangent_model);

Activation Checkpointing (checkpoint and remat)

Wrap deep blocks (such as Transformer layers) in checkpoint (or its alias remat) to drop intermediate activations after forward and recompute them behind stablehlo.optimization_barrier during backward. Outside grad, checkpoint runs the closure directly with zero overhead.

let h = checkpoint(|t| block.forward(&t), &h);

Custom Derivatives (custom_vjp)

Attach a custom backward pass to any forward function with custom_vjp(&input, fwd, bwd). fwd returns (output, residuals), and bwd(residuals, cotangent) returns gradients matching input. It composes with jit, vmap, checkpoint, while_loop, and higher-order grad.

// Straight-through estimator for rounding
let q = custom_vjp(
    &x,
    |t| (t.round(), ()),
    |(), cotangent| cotangent,
);

Vectorization (vmap)

vmap turns a single-example function into a batched one along axis 0 without manual batch bookkeeping.

// Per-example gradients in two lines
let per_example_grads = vmap(
    |(xi, ti): (Tensor, Tensor)| grad(|w| mse(&w.matmul(&xi), &ti), &weights),
    &(batch_x, batch_y),
);

Compiled Loops and Chunked Execution (for_loop, scan, map_chunks, and while_loop)

for_loop compiles a fixed-count loop into a single stablehlo.while op on device, avoiding host round-trips between steps.

let trained = for_loop(100, model, |_step, mut m| {
    let grads = grad(|p| p.loss(&x, &y), &m);
    m.update_in_place(&grads, 0.01);
    m
});

Inside grad, for_loop uses compiled reverse-mode differentiation without unrolling. Compiled graph size stays O(1) regardless of step count, per-step internal activations are recomputed during the reverse stablehlo.while pass, carried states are recorded in a tape of size O(steps * state), stacked per-layer weights accumulate via O(1) in-place scatter-add instead of full-stack tensor additions, and large FP8 stacked weights automatically accumulate outer gradients in scaled 1-byte F8E5M2 (cutting loop gradient HBM in half).

When device HBM has headroom (such as B200 or H200), use for_loop_auto or scan_auto (backed by auto_ckpt_steps, for_loop_selective, and scan_selective) to keep trailing layers uncheckpointed and skip backward activation recomputation automatically (override with JACOBI_CKPT_LAYERS=<N> or JACOBI_AUTO_CKPT_MULT=<M>).

For sequence recurrences that consume a leading axis [T, ...] and collect per-step outputs [T, ...], use scan.

let (final_h, ys) = scan(&xs, h0, |h, x_t| {
    let next = (h.matmul(&wh) + x_t).tanh();
    (next.clone(), next)
});

To cap peak activation memory across a large batch or sequence axis without rewriting your model, use map_chunks(chunk_size, &inputs, |chunk| ...). It slices axis 0 into chunks of at most chunk_size, wraps each chunk in checkpoint during grad, and concatenates outputs along axis 0.

let embeddings = map_chunks(16, &images, |chunk| encoder.forward(&chunk));

For condition-driven loops, use while_loop(init, |state| cond, |state| body).

Compiled Conditionals (cond and switch)

Use cond (stablehlo.if) for dynamic two-way branching and switch (stablehlo.case) for multi-way indexed dispatch on device. Both execute only the taken branch during forward and reverse passes. Under vmap with a per-element predicate, cond lowers automatically to elementwise select.

let out = cond(
    &pred,
    &x,
    |t| (&t * &t).sum(),
    |t| (&t * 3.0).sum(),
);

let b0 = |t: Tensor| &t * 2.0;
let b1 = |t: Tensor| &t * &t;
let b2 = |t: Tensor| t.relu();
let picked = switch(&branch_idx, &x, &[&b0, &b1, &b2]);