Transforms and Distributed¶
Reference for jacobi::transform covering compilation, reverse-mode and forward-mode autodiff, low-rank gradients, vectorization, compiled control flow, pmap, and SPMD shard_map.
Compilation (jit, eval, eval_shape)¶
| API | Signature | Description |
|---|---|---|
jit |
jit<I: Module, O: Module>(f: impl Fn(I) -> O) -> JitFn<I, O, F> |
Compile a Rust closure once per (engine, precision, autocast, shapes, dtypes) signature with in-memory LRU and on-disk caching plus automatic buffer donation |
jit_autocast |
jit_autocast(dtype: Dtype, f) -> JitFn<I, O, F> |
Equivalent to jit(f).autocast(dtype) |
jit_on |
jit_on(engine: &Engine, f) -> JitFn<I, O, F> |
Pin compilation and execution to a specific Engine |
JitFn methods |
.donate(bool), .donate_strict(bool), .donation_copies(), .autocast(Dtype), .max_cache_entries(usize), .clear_cache(), .cache_len(), .compile_for(&I) -> Result<String>, .call(I) -> Result<O>, .call_async(I) -> Result<PendingCall<O>>, .mlir(&I) -> Result<String> |
Configure donation/autocast/cache bounds, pre-compile AOT with Tensor::spec, or execute synchronously/asynchronously |
PendingCall<O> |
.is_ready() -> Result<bool>, .wait(self) -> Result<O> |
Async execution handle for overlapping host I/O with device compute |
eval |
eval<O: Module>(f: impl FnOnce() -> O) -> Result<O> |
Trace, compile, and run a one-off closure |
eval_shape |
eval_shape<I: Module, O: Module>(input: &I, f: impl Fn(I) -> O) -> Result<Vec<TensorSpec>> |
Infer output shapes and dtypes with zero buffer allocation or compilation |
Automatic Differentiation and Vectorization¶
| API | Signature | Description |
|---|---|---|
grad |
grad<P: Module>(f: impl Fn(P) -> Tensor, params: &P) -> P |
Reverse-mode gradient with respect to any Tensor, tuple, or #[module] (composable for higher-order derivatives) |
value_and_grad |
value_and_grad<P: Module>(f: impl Fn(P) -> Tensor, params: &P) -> (Tensor, P) |
Compute scalar loss and gradient in one reverse pass |
jvp |
jvp<I: Module, O: Module>(f, primals: &I, tangents: &I) -> (O, O) |
Forward-mode Jacobian-vector product in a single pass |
hvp |
hvp<P: Module>(f, primals: &P, tangents: &P) -> P |
Hessian-vector product via forward-over-reverse autodiff |
jacobian / jacfwd |
jacobian(f, &x) -> Tensor, jacfwd(f, &x) -> Tensor |
Reverse-mode and forward-mode full Jacobian matrices |
hessian |
hessian(f, &x) -> Tensor |
Full second-derivative Hessian matrix |
checkpoint / remat |
checkpoint<I: Module, O: Module>(f: impl Fn(I) -> O, input: &I) -> O |
Activation checkpointing behind stablehlo.optimization_barrier (zero overhead outside grad) |
custom_vjp |
custom_vjp<I, O, R>(input: &I, fwd: impl Fn(I) -> (O, R), bwd: impl Fn(R, O) -> I) -> O |
Attach custom analytical or FFI backward pass; composes with jit, vmap, for_loop, and higher-order grad |
vmap |
vmap<I: Module, O: Module>(f: impl Fn(I) -> O, inputs: &I) -> O |
Vectorize a single-example function over axis 0 |
Low-Rank Memory-Efficient Gradients (EfficientGrad)¶
| API | Signature | Description |
|---|---|---|
efficient_grad |
efficient_grad<P: Module>(f, params: &P, rank: usize) -> EfficientGrad<P> |
Compute rank-r factored gradients for 2D/3D/4D weight matrices |
value_and_efficient_grad |
value_and_efficient_grad<P: Module>(f, params: &P, rank: usize) -> (Tensor, EfficientGrad<P>) |
Scalar loss plus low-rank factored gradients |
efficient_grad_with / value_and_efficient_grad_with |
...(f, params: &P, cfg: EfficientGradConfig) |
Customize rank, power_iters, and min_dim |
value_and_efficient_grad_warm |
value_and_efficient_grad_warm(f, params: &P, bases: &[Option<Tensor>], cfg) |
Warm-started subspace iteration from previous orthonormal bases |
EfficientGradConfig |
EfficientGradConfig::new(rank).power_iters(1).min_dim(2 * rank) |
Subspace approximation settings |
EfficientGrad<M> |
.to_dense(&template), .memory_bytes(), .dense_memory_bytes(), .compression_ratio(), .scale(f64), .add_in_subspace(&other) |
Implements Module so low-rank gradients cross jit and for_loop without dense expansion |
FactoredTensor |
.is_low_rank(), .shape(), .rank(), .to_dense(), .byte_size(), .dense_byte_size(), .scale(f64) |
Single dense or left @ right factored leaf |
Compiled Control Flow¶
| API | Signature | Description |
|---|---|---|
for_loop |
for_loop<S: Module>(steps: usize, init: S, body: impl Fn(Tensor, S) -> S) -> S |
Fixed-count stablehlo.while loop. Inside grad, automatically uses O(1)-graph checkpointed reverse While with O(1) in-place scatter-add and scaled F8E5M2 outer gradient accumulation for large FP8 stacked weights |
for_loop_selective / for_loop_auto |
for_loop_selective(steps, ckpt_steps, init, body), for_loop_auto(steps, init, body) |
Checkpoints only the first ckpt_steps iterations and unrolls trailing layers without backward recomputation (for_loop_auto computes ckpt_steps via auto_ckpt_steps) |
scan / scan_selective / scan_auto |
scan(&xs, init, body), scan_selective(&xs, ckpt_steps, init, body), scan_auto(&xs, init, body) |
Sequence recurrence over leading axis [T, ...] collecting per-step outputs [T, ...], with optional manual or HBM-aware selective checkpointing |
auto_ckpt_steps |
auto_ckpt_steps<S: Module>(steps: usize, sample_state: &S) -> usize |
Estimates how many leading iterations to checkpoint from device HBM limit (JACOBI_CKPT_LAYERS and JACOBI_AUTO_CKPT_MULT overrides) |
map_chunks |
map_chunks<I: Module, O: Module>(chunk_size: usize, inputs: &I, f: impl Fn(I) -> O) -> O |
Process axis 0 in chunks of at most chunk_size with per-chunk checkpoint rematerialization during grad and concatenate outputs along axis 0 |
while_loop |
while_loop<S: Module>(init: S, cond: impl Fn(&S) -> Tensor, body: impl Fn(S) -> S) -> S |
Data-dependent stablehlo.while loop |
cond |
cond<I: Module, O: Module>(pred: &Tensor, operand: &I, on_true, on_false) -> O |
Differentiable, vmap-safe stablehlo.if conditional |
switch |
switch<I: Module, O: Module>(index: &Tensor, operand: &I, branches: &[&dyn Fn(I) -> O]) -> O |
Differentiable multi-way stablehlo.case dispatch |
Data Parallelism (pmap) and Sharded<M>¶
pmap(f)/pmap_on(&engine, f)returnsPmapFn<I, O, F>(.num_devices(n),.donate(bool),.donate_strict(bool),.donation_copies(),.autocast(Dtype),.max_cache_entries(usize),.clear_cache(),.cache_len(),.call(Vec<I>) -> Result<Vec<O>>,.call_sharded(Sharded<I>) -> Result<Sharded<O>>,.mlir(&I)).Sharded<M>typed per-device handle (Sharded::from_shards,Sharded::from_fn,Sharded::replicate,Sharded::replicate_n,.len(),.shards(),.into_shards(),.first(),.into_first(),.unreplicate(),.map,.try_map,.into_map,.try_into_map,.zip,.zip3,.unzip,.unzip3).- Placement helpers
replicate(&m),replicate_n(&m, n),unreplicate(&replicas),shard_batch(&x),shard_batch_n(&x, n),gather_shards(&shards). - Collectives
psum(&x),pmean(&x),pmax(&x),pmin(&x),all_gather(&t, dim),replica_id().
SPMD Sharding (Mesh, NamedSharding, shard_map)¶
| API | Signature | Description |
|---|---|---|
Mesh::new |
Mesh::new(axis_names: &[&str], shape: &[usize]) -> Result<Mesh> |
Multi-dimensional named device grid (e.g. Mesh::new(&["dp", "tp"], &[2, 2])) |
Mesh::from_devices |
Mesh::from_devices(axis_names, shape, device_ids: Vec<usize>) -> Result<Mesh> |
Explicit PJRT device ordering |
Mesh::data_parallel |
Mesh::data_parallel(axis_name: &str) -> Result<Mesh> |
1D mesh spanning all global PJRT devices |
Mesh::hybrid_dp_ep |
Mesh::hybrid_dp_ep() -> Result<Mesh> |
Topology-aware 2D ["dp", "ep"] mesh placing "ep" intra-node (NVLink) and "dp" inter-node |
Mesh queries |
.axis_names(), .shape(), .device_ids(), .size(), .axis_pos(name), .axis_size(name), .coords_of(idx), .flat_index(&coords), .axis_groups(name) |
Introspect mesh topology and replica groups |
PartitionSpec |
PartitionSpec::new(&[Option<&str>]), by_axis("dp"), replicated() |
Maps tensor dimensions to mesh axis names |
NamedSharding |
NamedSharding::new(mesh, spec) (.shard_tensor, .gather_tensor, .mhlo_sharding) |
Binds a PartitionSpec to a Mesh |
shard_map / shard_map_on |
shard_map(mesh, in_specs, out_specs, f) -> ShardMapFn (.donate, .donate_strict, .donation_copies, .autocast, .max_cache_entries, .clear_cache, .cache_len, .call, .call_sharded, .call_sharded_handle, .compile_for, .mlir) |
Explicit per-shard SPMD computation over a named Mesh |
with_sharding_constraint |
with_sharding_constraint(&t, &named_sharding) -> Tensor |
Emit XLA GSPMD stablehlo.custom_call @Sharding annotation |
| Named-axis collectives | axis_index(ax), psum_axis(&x, ax), pmean_axis(&x, ax), pmax_axis(&x, ax), pmin_axis(&x, ax), all_gather_axis(&t, dim, ax), all_to_all_axis(&t, ax, split_dim, concat_dim) |
Differentiable StableHLO collectives over any mesh axis (exact adjoint VJP for all_to_all_axis swaps split_dim and concat_dim) |
| Synchronization | barrier() -> Result<()>, barrier_on(&engine) -> Result<()> |
Synchronize all participating devices |