Distributed Training¶
Jacobi scales from a single workstation to multi-node GPU and TPU clusters directly over XLA and PJRT without external NCCL wrappers or separate launcher frameworks. Every collective (psum, pmean, all_gather, all_to_all_axis) lowers to native StableHLO collectives and differentiates automatically through grad, value_and_grad, and EfficientAdamW.
Choosing a Parallelism Strategy¶
| Strategy | API | Best Fit | Communication |
|---|---|---|---|
| Data Parallel (DP) | pmap + replicate + shard_batch |
Models that fit on 1 accelerator across 2 to 8+ devices | pmean gradient all-reduce |
| 1D / 2D SPMD (DP, TP, FSDP) | Mesh + PartitionSpec + shard_map |
Sharded weights, tensor parallelism, or FSDP | psum_axis, pmean_axis, all_gather_axis |
| Hybrid Data + Expert Parallel | init_distributed + Mesh::hybrid_dp_ep() + shard_map |
Multi-node sparse MoE and large LLMs (26B to 283B+) | Intra-node NVLink all_to_all_axis + inter-node "dp" sync |
Device Discovery and Local Simulation¶
Query local and cluster-wide PJRT devices with devices(), num_devices(), num_global_devices(), num_processes(), and process_index(). Upload directly to a specific device with Tensor::from_host_on, Tensor::from_f32_on (and typed from_*_on variants), or move existing tensors and modules with Tensor::to_device(idx), Module::to_device(idx), and Tensor::device_index().
use jacobi::prelude::*;
let devs = devices()?;
println!(
"process {}/{} sees {} local / {} global devices",
process_index(),
num_processes(),
devs.len(),
num_global_devices()?,
);
let x = Tensor::randn(&[8, 64]).to_device(0)?;
To develop and test multi-device pmap or shard_map code locally on a CPU machine, set XLA_FLAGS to simulate multiple virtual devices.
JACOBI_BACKEND=cpu XLA_FLAGS="--xla_force_host_platform_device_count=8" cargo test --test distributed
Single-Node Data Parallelism (pmap)¶
pmap compiles a single program across all addressable PJRT devices and executes every replica simultaneously. Keep model weights and optimizer states resident on device across steps with replicate and shard_batch, synchronize gradients and losses with pmean, and fetch the trained weights with unreplicate.
use jacobi::prelude::*;
#[module]
struct Mlp {
fc1: Linear,
fc2: Linear,
}
impl Mlp {
fn new(dim: usize) -> Self {
Self {
fc1: Linear::new(dim, dim * 4),
fc2: Linear::new(dim * 4, dim),
}
}
fn forward(&self, x: &Tensor) -> Tensor {
self.fc2.forward(&self.fc1.forward(x).silu())
}
}
fn main() -> Result<()> {
let model = Mlp::new(1024);
let opt = AdamW::new(&model, 3e-4);
let mut models = replicate(&model)?;
let mut opts = replicate(&opt)?;
let train_step = pmap(|(mut m, mut o, x, y): (Mlp, AdamW<Mlp>, Tensor, Tensor)| {
let (loss, grads) = value_and_grad(|p| nn::mse_loss(&p.forward(&x), &y), &m);
let grads = pmean(&grads);
let loss = pmean(&loss);
o.step(&mut m, &grads);
(m, o, loss)
});
for step in 0..100 {
let x_shards = shard_batch(&Tensor::randn(&[64, 1024]))?;
let y_shards = shard_batch(&Tensor::randn(&[64, 1024]))?;
let inputs: Vec<_> = models
.into_iter()
.zip(opts)
.zip(x_shards)
.zip(y_shards)
.map(|(((m, o), x), y)| (m, o, x, y))
.collect();
let outputs = train_step.call(inputs)?;
let loss = outputs[0].2.item_f32()?;
models = Vec::with_capacity(outputs.len());
opts = Vec::with_capacity(outputs.len());
for (m, o, _) in outputs {
models.push(m);
opts.push(o);
}
if step % 10 == 0 {
println!("step {step} loss {loss:.4}");
}
}
let trained = unreplicate(&models)?;
trained.save("mlp.safetensors")?;
Ok(())
}
Use replicate_n(&model, n) and shard_batch_n(&batch, n) with pmap_on when targeting a subset of devices, and gather_shards(&outputs) to concatenate per-device outputs back into one host-accessible tensor.
Typed Per-Device Handles (Sharded<M>)¶
To avoid manually zipping and unzipping raw Vec<M> device lists, wrap per-device states and batches in Sharded<M> and invoke PmapFn::call_sharded or ShardMapFn::call_sharded_handle. Pair Sharded::from_fn with Tensor::from_f32_on / Tensor::from_host_on to upload each device's microbatch directly to its target accelerator.
let mut models = Sharded::replicate(&model)?;
let mut opts = Sharded::replicate(&opt)?;
let batches = Sharded::from_fn(num_devices()?, |dev| {
let x = Tensor::from_f32_on(&host_x[dev], &[micro_bs, dim], dev)?;
let y = Tensor::from_f32_on(&host_y[dev], &[micro_bs, dim], dev)?;
Ok((x, y))
})?;
let (next_models, next_opts, losses) = train_step
.call_sharded(models.zip3(opts, batches)?)?
.unzip3();
let loss = losses.first().item()?;
SPMD Sharding (Mesh, PartitionSpec, shard_map)¶
Define multi-dimensional device grids with Mesh, describe axis layouts with PartitionSpec and NamedSharding, and run explicit local-shard SPMD programs with shard_map. Named-axis collectives (psum_axis, pmean_axis, pmax_axis, pmin_axis, all_gather_axis, all_to_all_axis, and axis_index) operate along any named mesh axis for tensor parallelism, FSDP, and expert parallelism.
use jacobi::prelude::*;
let mesh = Mesh::new(&["dp", "tp"], &[2, 2])?;
let tp_dp = shard_map(
mesh,
vec![
PartitionSpec::new(&[Some("dp"), Some("tp")]),
PartitionSpec::new(&[Some("tp"), None]),
],
vec![PartitionSpec::new(&[Some("dp"), None])],
|(x_loc, w_loc): (Tensor, Tensor)| {
let partial = x_loc.matmul(&w_loc);
psum_axis(&partial, "tp")
},
);
let y_global = tp_dp.call((x_global, w_global))?;
- Use
.call(global_input)to auto-shard global inputs according to the inputPartitionSpecand gather outputs back. - Use
.call_sharded(per_device_inputs)or.call_sharded_handle(Sharded<I>)in training loops so model shards, optimizer states, and data batches stay resident on each device with zero host round-trips. - Annotate intermediate tensors with
with_sharding_constraint(&t, &NamedSharding::new(mesh, spec))to emitstablehlo.custom_call @Shardinghints for XLA GSPMD.
Multi-Node Training and Hybrid DP x EP¶
Initialize multi-node PJRT coordination before creating tensors or meshes via init_distributed(coordinator_addr, num_processes, process_id)?, or set JACOBI_COORDINATOR_ADDR, JACOBI_NUM_PROCESSES, and JACOBI_PROCESS_ID in the environment. Process 0 starts the built-in PJRT coordination key-value service automatically and every other host connects to it.
Mesh::hybrid_dp_ep() constructs a topology-aware 2D ["dp", "ep"] mesh where intra-node devices (NVLink) form the "ep" axis and inter-node processes (InfiniBand or Ethernet) form the "dp" axis. For example, 2 nodes x 8 H200 maps to dp=2, ep=8.
Combine Mesh::hybrid_dp_ep() with nn::moe_swiglu_dispatch_all_to_all and EfficientAdamW::value_and_grad_hybrid to keep high-frequency MoE token routing inside NVLink while synchronizing replicated attention weights across ["ep", "dp"] and sharded expert weights across ["dp"] in compressed low-rank space.
use jacobi::prelude::*;
#[module]
struct MoeShard {
attn_proj: Linear,
router: Tensor,
w_gate: Tensor,
w_up: Tensor,
w_down: Tensor,
}
impl MoeShard {
fn loss(&self, x: &Tensor, targets: &Tensor, n_experts: usize, ep_size: usize) -> Tensor {
let h = self.attn_proj.forward(x);
let logits = h.matmul(&self.router);
let (top_weights, top_idx) = logits.softmax().top_k(2);
let moe_out = nn::moe_swiglu_dispatch_all_to_all(
&h,
&top_idx,
&top_weights,
&self.w_gate,
&self.w_up,
&self.w_down,
n_experts,
ep_size,
Some("ep"),
MoeDispatchConfig::default(),
);
nn::mse_loss(&moe_out, targets)
}
}
fn main() -> Result<()> {
let coord = std::env::var("JACOBI_COORDINATOR_ADDR")?;
let n_procs: usize = std::env::var("JACOBI_NUM_PROCESSES")?.parse().unwrap();
let proc_id: usize = std::env::var("JACOBI_PROCESS_ID")?.parse().unwrap();
init_distributed(coord, n_procs, proc_id)?;
let mesh = Mesh::hybrid_dp_ep()?;
let ep_size = mesh.axis_size("ep")?;
let local_devs = num_devices()?;
let n_experts = 64;
let init_fn = shard_map(
mesh.clone(),
vec![PartitionSpec::replicated()],
vec![PartitionSpec::replicated()],
move |seed_dummy: Tensor| {
let _ = seed_dummy;
let e_local = n_experts / ep_size;
let shard = MoeShard {
attn_proj: Linear::new(2048, 2048),
router: Tensor::randn(&[2048, n_experts]).to_bf16(),
w_gate: Tensor::randn(&[e_local, 2048, 4096]).to_bf16(),
w_up: Tensor::randn(&[e_local, 2048, 4096]).to_bf16(),
w_down: Tensor::randn(&[e_local, 4096, 2048]).to_bf16(),
};
let opt = EfficientAdamW::new(&shard, 3e-4, 32);
(shard, opt)
},
);
let init_in: Vec<Tensor> = (0..local_devs)
.map(|d| Tensor::scalar(0.0).to_device(d))
.collect::<Result<_>>()?;
let mut state = init_fn.call_sharded(init_in)?;
let train_step = shard_map(
mesh,
vec![PartitionSpec::replicated()],
vec![PartitionSpec::replicated()],
move |(mut shard, mut opt, x, y): (MoeShard, EfficientAdamW<MoeShard>, Tensor, Tensor)| {
let (loss, eff_grads) = opt.value_and_grad_hybrid(
|p| p.loss(&x, &y, n_experts, ep_size),
&shard,
&["ep", "dp"],
|name| {
if name.starts_with("w_gate")
|| name.starts_with("w_up")
|| name.starts_with("w_down")
{
vec!["dp"]
} else {
vec!["ep", "dp"]
}
},
);
opt.step(&mut shard, &eff_grads);
(shard, opt, loss)
},
);
for step in 0..100 {
let x_local: Vec<Tensor> = (0..local_devs)
.map(|d| Tensor::randn(&[4, 2048, 2048]).to_bf16().to_device(d))
.collect::<Result<_>>()?;
let y_local: Vec<Tensor> = (0..local_devs)
.map(|d| Tensor::randn(&[4, 2048, 2048]).to_bf16().to_device(d))
.collect::<Result<_>>()?;
let inputs: Vec<_> = state
.into_iter()
.zip(x_local)
.zip(y_local)
.map(|(((s, o), x), y)| (s, o, x, y))
.collect();
barrier()?;
let outputs = train_step.call_sharded(inputs)?;
let loss = outputs[0].2.item_f32()?;
state = outputs.into_iter().map(|(s, o, _)| (s, o)).collect();
if proc_id == 0 && step % 10 == 0 {
println!("step {step} loss {loss:.4}");
}
}
Ok(())
}
Launching Across Multiple Nodes¶
Run the same compiled binary on every node with identical JACOBI_COORDINATOR_ADDR (reachable IP and open TCP port on process 0), shared JACOBI_COORDINATOR_TOKEN (required by default for coordinator auth), and each host's unique JACOBI_PROCESS_ID.
# Node 0
JACOBI_COORDINATOR_ADDR=10.0.0.1:29500 JACOBI_COORDINATOR_TOKEN=your-cluster-secret \
JACOBI_NUM_PROCESSES=2 JACOBI_PROCESS_ID=0 cargo run --release
# Node 1
JACOBI_COORDINATOR_ADDR=10.0.0.1:29500 JACOBI_COORDINATOR_TOKEN=your-cluster-secret \
JACOBI_NUM_PROCESSES=2 JACOBI_PROCESS_ID=1 cargo run --release
On Slurm clusters, map SLURM_PROCID and SLURM_NTASKS directly into each rank.
srun --nodes=2 --ntasks-per-node=1 --gpus-per-node=8 bash -c '
MASTER_ADDR=$(scontrol show hostnames "$SLURM_JOB_NODELIST" | head -n 1)
JACOBI_COORDINATOR_ADDR="${MASTER_ADDR}:29500" \
JACOBI_COORDINATOR_TOKEN="$CLUSTER_SECRET" \
JACOBI_NUM_PROCESSES="$SLURM_NTASKS" \
JACOBI_PROCESS_ID="$SLURM_PROCID" \
./target/release/my_trainer
'
On hosts with multiple network interfaces or without InfiniBand, set NCCL_SOCKET_IFNAME=eth0 (or your cluster's inter-node interface name) and NCCL_IB_DISABLE=1 if running over TCP/Ethernet. See examples/deepseek_v4_flash.rs (283B DP=2 x EP=8 on 16x H200) and examples/inkling_mini_2_26b.rs (26B EP=8 on 8x H200) for full production scripts.
Ahead-of-Time Pre-Compilation (Tensor::spec and compile_for)¶
On large models that approach GPU HBM capacity, compile your JitFn or ShardMapFn before allocating real weights or optimizer states using zero-allocation Tensor::spec(&shape, dtype) placeholders alongside Adam::spec_for, AdamW::spec_for, or EfficientAdamW::spec_for.
use jacobi::prelude::*;
let shard_spec = MoeShard {
attn_proj: Linear {
w: Tensor::spec(&[2048, 2048], Dtype::F32),
b: Tensor::spec(&[2048], Dtype::F32),
},
router: Tensor::spec(&[2048, 64], Dtype::BF16),
w_gate: Tensor::spec(&[8, 2048, 4096], Dtype::BF16),
w_up: Tensor::spec(&[8, 2048, 4096], Dtype::BF16),
w_down: Tensor::spec(&[8, 4096, 2048], Dtype::BF16),
};
let opt_spec = EfficientAdamW::spec_for(&shard_spec, 3e-4, 32);
let x_spec = Tensor::spec(&[4, 2048, 2048], Dtype::BF16);
let y_spec = Tensor::spec(&[4, 2048, 2048], Dtype::BF16);
let _mlir = train_step.compile_for(&(shard_spec, opt_spec, x_spec, y_spec))?;
Subsequent .call(...) and .call_sharded(...) invocations with matching shapes and dtypes hit the compiled executable cache immediately without competing for peak HBM during XLA compilation.
Collectives and Synchronization Reference¶
| Collective | Context | Behavior |
|---|---|---|
psum(&x) / pmean(&x) |
pmap |
Sum or mean across all replicas (Module or Tensor) |
pmax(&x) / pmin(&x) |
pmap |
Elementwise max or min across all replicas |
all_gather(&x, axis) |
pmap |
Concatenate shards along axis across all replicas |
replica_id() |
pmap |
Scalar I32 replica index on each device |
psum_axis(&x, axis) / pmean_axis(&x, axis) |
shard_map |
Sum or mean along named mesh axis |
pmax_axis(&x, axis) / pmin_axis(&x, axis) |
shard_map |
Elementwise max or min along named mesh axis |
all_gather_axis(&x, axis, dim) |
shard_map |
Concatenate local shards along tensor dim over mesh axis |
all_to_all_axis(&x, axis, split_dim, concat_dim) |
shard_map |
Split split_dim, exchange across mesh axis, concatenate on concat_dim |
axis_index(axis) |
shard_map |
Scalar I32 coordinate of this device along mesh axis |
barrier() / barrier_on(&engine) |
Any | Host-level synchronization barrier across participating devices |
Checkpointing Distributed Models¶
- For replicated (
pmap) models, extract replica0withunreplicate(&models)?and save fromprocess_index() == 0viatrained.save("checkpoint.safetensors")?. - For sharded (
shard_map) models, save per-shard checkpoints tagged by(process_index(), local_device_idx)or gather replicated layers once on process0while saving sharded expert tensors per rank.
if process_index() == 0 {
let trained = unreplicate(&models)?;
trained.save("checkpoint.safetensors")?;
}
barrier()?;
Runtime Environment Variables¶
| Variable | Purpose |
|---|---|
JACOBI_COORDINATOR_ADDR |
Multi-node coordinator host:port (for example 10.0.0.1:29500) |
JACOBI_COORDINATOR_TOKEN |
Required shared secret authenticating coordinator requests (opt out only via JACOBI_COORDINATOR_ALLOW_UNAUTHENTICATED=1) |
JACOBI_NUM_PROCESSES |
Total number of host processes in the distributed job |
JACOBI_PROCESS_ID |
Zero-based rank of this host (0..num_processes) |
JACOBI_GPU_MEMORY_FRACTION |
Fraction of GPU HBM reserved by PJRT BFC allocator (for example 0.92) |
JACOBI_GPU_PREALLOCATE |
Set to 0 or false to disable upfront GPU memory preallocation |
JACOBI_CUDNN_FMHA |
Set to 0 to disable cuDNN FlashAttention-2/3 and use tiled fallback |
JACOBI_FP8_BWD |
Override hardware auto-detection (1 on Blackwell/TPU, 0 on Hopper) for FP8 backward GEMMs |
JACOBI_FP8_GRAD_ACC |
Set to 0 to disable scaled F8E5M2 outer loop gradient accumulation |
JACOBI_LOGS |
Set to 1 to re-enable raw XLA and PJRT native logs (silenced by default) |
JACOBI_DEBUG_NANS |
Set to 1 to fail immediately when any op produces NaN or Inf |
FlashAttention and Custom Kernels (nn::flash_attention, ffi_call)¶
Use nn::flash_attention(&q, &k, &v, causal, scale) for MHA, GQA, and MQA attention and nn::flash_attention_varlen(&q, &k, &v, &q_lens, &kv_lens, causal, scale) for padded variable-length batches. On CUDA with BF16 or F16 inputs (16 <= D <= 256 multiple of 8, S >= 64), nn::flash_attention automatically dispatches to NVIDIA cuDNN FlashAttention-2/3 (__cudnn$fmhaSoftmax forward and __cudnn$fmhaSoftmaxBackward backward via custom_vjp, falling back cleanly to exact analytical lower-triangular tiled FlashAttention-2 backward for 128 < D <= 256 on Blackwell; set JACOBI_CUDNN_FMHA=0 to disable). On larger head dims (such as D = 512), CPU, Metal, TPU, or F32, it runs causal lower-triangular block-tiled FlashAttention with remat for S >= 1024.
Register custom Rust, C++, CUDA, or PTX kernels directly with the loaded PJRT plugin via PJRT_FFI_Extension and invoke them inside jit with zero host copies.
use jacobi::ffi::{XlaFfiBuffer, XlaFfiCallFrame};
unsafe extern "C" fn scale_kernel(frame: *mut XlaFfiCallFrame) -> *mut std::ffi::c_void {
unsafe {
let f = &mut *frame;
if f.handle_metadata(0) {
return std::ptr::null_mut();
}
let inp = &*(*f.args.args as *const XlaFfiBuffer);
let out = &*(*f.rets.rets as *const XlaFfiBuffer);
let n = inp.numel();
let src = std::slice::from_raw_parts(inp.data as *const f32, n);
let dst = std::slice::from_raw_parts_mut(out.data as *mut f32, n);
for i in 0..n {
dst[i] = src[i] * 2.0;
}
std::ptr::null_mut()
}
}
register_ffi_handler("my_scale", scale_kernel)?;
let y = ffi_call_with_vjp(
&x,
|a| (ffi_call_one("my_scale", &[&a], &a.shape(), a.dtype(), ""), ()),
|(), cot| &cot * 2.0,
);
DLPack Tensor Interop (to_dlpack, from_dlpack)¶
Share device buffers with PyTorch, NumPy, JAX, CuPy, or C/C++ libraries using standard DLManagedTensor capsules. When the PJRT backend exposes external buffer pointers (PJRT_Buffer_OpaqueDeviceMemoryDataPointer), to_dlpack exports zero-copy directly from device memory and releases the reference inside the DLPack deleter.
To hand ownership to an external C or Python runtime, call capsule.into_raw(). To import a raw pointer from another runtime, call unsafe { Tensor::from_dlpack_ptr(ptr) }. Strided views and non-zero byte_offset headers are handled automatically.
Debugging and Memory Profiling (debug_nans, debug_print, memory_stats)¶
with_debug_nans(true, || ...)orset_debug_nans(true)(orJACOBI_DEBUG_NANS=1) checks every floating-point output from eager ops,eval,jit,pmap, andshard_map, returning an error as soon as anyNaNorInfappears.debug_print("label", &tensor)andtensor.debug_print("label")print tensor shapes, dtypes, and values both eagerly and inside compiledjitandgradfunctions without breaking autodiff. Capture lines programmatically withwith_debug_print_capture.memory_stats(),memory_stats_on(dev_idx), andall_memory_stats()queryPJRT_Device_MemoryStatsfor live allocator usage, peak bytes, allocation counts, and pool limits on GPU and TPU backends.