Distributed Overview, torchrun & Elastic
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Training on more than one device means several Python processes that must agree on who they are, find each other, exchange tensors and fail together or recover together. PyTorch splits this into layers: a launcher (torchrun) that starts and supervises processes, a communication library (torch.distributed, also called c10d) with collective operations over back ends such as NCCL and Gloo, and parallelism wrappers built on top (DDP, FSDP2, tensor and pipeline parallelism). This page is the map of those layers and covers the launcher in detail. The wrappers have their own pages: DistributedDataParallel, FSDP2 (fully_shard) and DTensor, Tensor & Pipeline Parallelism. The concepts (data parallelism, all-reduce, sharding, batch size and learning-rate scaling) are explained framework-neutrally in Distributed Training Concepts.
Targeted versions: Python 3.13 and PyTorch 2.15. Distributed code needs several processes and normally several GPUs. The examples were run on Python 3.13 with PyTorch 2.15 on 2026-10-31 as two CPU processes launched by torchrun with the Gloo back end, which is also the way to smoke-test your own logic without GPUs.
The map
The official distributed overview groups the pieces as follows.
| Piece | Role |
|---|---|
DDP ( |
Replicates the model in every process; each replica trains on different data and gradients are averaged with an all-reduce. |
FSDP2 ( |
Shards parameters, gradients and optimizer state across processes so models too large for one GPU can train. |
Tensor parallelism (TP) and pipeline parallelism (PP) |
Split the model itself across devices; can be combined with data parallelism into multi-dimensional parallelism. |
DTensor |
A tensor that is sharded or replicated over a device mesh and redistributes data as operations need it. |
DeviceMesh |
A multi-dimensional arrangement of devices that manages the process groups used for collective communication. |
c10d ( |
The communication layer: collectives such as |
torchrun |
The launcher that starts the processes on local and remote machines, sets their environment and restarts them on failure. |
The official decision guidance is short, and the diagram follows it:
Start with DDP. Move to FSDP2 when memory forces you. Add tensor or pipeline parallelism only when FSDP2 alone stops scaling. Data-parallel training works together with automatic mixed precision (Mixed Precision with torch.amp).
Vocabulary
-
Process group: a set of processes that take part in collective operations together. The default (world) group contains all processes.
-
World size: number of processes in the group.
-
Rank: a process’s global index, from 0 to
world_size - 1. Rank 0 is conventionally the one that logs and saves checkpoints. -
Local rank: the process’s index within its node. It selects the GPU on that node.
-
Node: a machine. Group rank (
GROUP_RANK) numbers the node’s worker group. -
Rendezvous: the mechanism by which workers discover each other and agree on ranks and world size.
-
Collective: an operation in which all ranks participate:
broadcast,all_reduce,reduce,all_gather,reduce_scatter,all_to_all,barrier. Every rank must call the same collectives in the same order, otherwise the job hangs.
Back ends
torch.distributed.init_process_group selects a back end. NCCL is the fastest and recommended back end for NVIDIA GPUs, both on one node and across nodes. Gloo works on CPU (and some GPU operations) and is the practical choice for tests and CPU-only training. Rather than hard-code a name, current tutorials ask PyTorch for the default back end of the active accelerator:
import torch
import torch.distributed as dist
acc = torch.accelerator.current_accelerator()
backend = torch.distributed.get_default_backend_for_device(acc)
dist.init_process_group(backend)
On a CPU-only machine current_accelerator() returns None; use "gloo" explicitly there. Other accelerators (ROCm builds use NCCL’s counterpart RCCL through the same name, Intel GPUs have their own back end) are summarised in Devices & Accelerators.
A first distributed script
With torchrun each process finds its identity in environment variables, so the script needs no rank arguments. This script initialises the group, runs three collectives and cleans up. It works with both Gloo on CPU and NCCL on GPU.
# collectives_demo.py
import os
import torch
import torch.distributed as dist
def main():
local_rank = int(os.environ["LOCAL_RANK"])
use_cuda = torch.cuda.is_available()
if use_cuda:
torch.cuda.set_device(local_rank)
backend = "nccl" if use_cuda else "gloo"
dist.init_process_group(backend)
rank = dist.get_rank()
world = dist.get_world_size()
device = torch.device("cuda", local_rank) if use_cuda else torch.device("cpu")
# all_reduce: every rank ends with the sum
t = torch.tensor([float(rank + 1)], device=device)
dist.all_reduce(t, op=dist.ReduceOp.SUM)
print(f"[rank {rank}/{world}] all_reduce -> {t.item()}")
# broadcast: everyone gets rank 0's tensor
b = torch.tensor([42.0 if rank == 0 else 0.0], device=device)
dist.broadcast(b, src=0)
# all_gather: collect one tensor from every rank
mine = torch.tensor([float(rank)], device=device)
gathered = [torch.zeros_like(mine) for _ in range(world)]
dist.all_gather(gathered, mine)
if rank == 0:
print("all_gather ->", [g.item() for g in gathered])
dist.barrier()
dist.destroy_process_group()
if __name__ == "__main__":
main()
torchrun --standalone --nproc-per-node=2 collectives_demo.py
On two CPU processes with Gloo it prints (the order of the rank lines can vary):
[rank 0/2] all_reduce -> 3.0 [rank 1/2] all_reduce -> 3.0 all_gather -> [0.0, 1.0]
Source: https://docs.pytorch.org/docs/stable/elastic/run.html and https://docs.pytorch.org/tutorials/intermediate/ddp_tutorial.html
Always call destroy_process_group() at the end. For NCCL, set the CUDA device (here torch.cuda.set_device(local_rank)) before creating the group so that each rank uses its own GPU.
torchrun
torchrun is a console script for python -m torch.distributed.run. It launches several worker processes per node, on CPU or GPU (one GPU per process), sets the environment each worker needs and supervises them. It replaces the older torch.distributed.launch, which should not be used in new code.
Environment variables
Each worker receives:
| Variable | Meaning |
|---|---|
|
Global rank of the worker. |
|
Rank within the node; use it to select the GPU. |
|
Total number of workers. |
|
Number of workers on the node (equal to |
|
Rank of the worker group, which is the node rank in the usual one-group-per-node case. |
|
Address and port of the host of rank 0, used by the default |
|
Number of worker group restarts so far. Useful to detect that you resumed after a failure. |
|
The configured restart limit and the job id. |
Because these variables are set for you, dist.init_process_group(backend) needs no rank or world_size arguments. Read ranks from the environment (or from dist.get_rank()), never hard-code them.
Main flags
| Flag | Meaning |
|---|---|
|
Processes per node: an integer, or |
|
Number of nodes: a fixed number, or a |
|
Single-node mode with no external rendezvous setup; the simplest way to run on one machine. |
|
Rendezvous back end. |
|
|
|
A job id shared by all nodes of the job. |
|
Maximum number of worker-group restarts after failures. |
|
Control where each worker’s stdout and stderr go and which ranks are shown. |
The documentation also lists --numa-binding and --log-line-prefix-template; run torchrun --help for the full list in your installation. Since PyTorch 2.0 torchrun passes --local-rank=<rank> to a script that accepts command-line arguments, and the dashed form is preferred over --local_rank, so scripts that parse the argument should accept both. Reading LOCAL_RANK from the environment avoids the issue.
Typical commands
# One node, one process per GPU
torchrun --standalone --nnodes=1 --nproc-per-node=gpu train.py
# Fixed-size, fault-tolerant job: up to 3 restarts
torchrun --nnodes=$NUM_NODES --nproc-per-node=$NUM_TRAINERS --max-restarts=3 \
--rdzv-id=$JOB_ID --rdzv-backend=c10d --rdzv-endpoint=$HOST_NODE_ADDR train.py
# Elastic job: runs with anywhere from 1 to 4 nodes
torchrun --nnodes=1:4 --nproc-per-node=$NUM_TRAINERS --max-restarts=3 \
--rdzv-id=$JOB_ID --rdzv-backend=c10d --rdzv-endpoint=$HOST_NODE_ADDR train.py
Run the same command on every node (changing nothing but the machine). HOST_NODE_ADDR is host:port of any node reachable by all others; the c10d rendezvous runs on that endpoint, which needs no separate service. On a cluster scheduler such as SLURM, derive the endpoint from the first host in the allocation and start one torchrun per node, as the DDP tutorial shows with srun.
Fault tolerance and elasticity
-
Fault tolerance (fixed size). The number of nodes is fixed. If any worker fails, all workers on all nodes are stopped and the whole group restarts, up to
--max-restartstimes. -
Elasticity (
--nnodes=min:max). Nodes may leave or join. On any change in membership the workers are stopped, a new worker group forms and the workers restart with newRANKandWORLD_SIZE.
In both cases all surviving workers are killed immediately on a failure or membership change, so training must resume from a checkpoint: save regularly and load the latest checkpoint at start-up. Do not assume rank or world size are constant across restarts; derive everything from the environment each time, and make the data sampler and learning-rate schedule depend on the global step restored from the checkpoint rather than on world size. Checkpointing sharded models is described in Distributed Checkpoint & Flight Recorder, and plain checkpoint files in Saving & Loading Models.
Data, seeds and logging
-
Use a
DistributedSamplerso each rank sees a different shard of the data, and callsampler.set_epoch(epoch)every epoch so shuffling differs between epochs. See Datasets & DataLoader. -
Seed every rank identically for model initialisation if you do not rely on DDP’s broadcast, and differently for data augmentation; see Reproducibility & Determinism.
-
Log and save only on rank 0 (
if dist.get_rank() == 0:) but keep all ranks in lock-step around collectives. Adist.barrier()after rank 0 writes a file makes the other ranks wait for it. -
Multiple DataLoader workers and NCCL or Gloo over InfiniBand are not fork-safe; the DDP reference advises the
forkserverorspawnstart method in that case.
Timeouts and hangs
The constructor, the forward pass and the backward pass of DDP are synchronisation points, so if one rank is much slower than the others (an uneven data shard, a long evaluation on rank 0) the others may hit the collective timeout. Pass a sufficiently large timeout (a datetime.timedelta) to init_process_group when skew is expected. A job that hangs rather than fails is usually a collective that not all ranks reach. Debugging tools for this, such as the NCCL flight recorder, are described in Distributed Checkpoint & Flight Recorder.
Useful environment variables while debugging are TORCH_DISTRIBUTED_DEBUG=DETAIL and NCCL_DEBUG=INFO; both are documented in the distributed package reference (confirm the exact semantics for your release there).
mp.spawn versus torchrun
The DDP tutorial shows two launch styles. With torch.multiprocessing.spawn, the script starts world_size processes itself and each receives its rank as an argument; this is convenient for notebooks and tests on one machine. With torchrun, an external launcher starts the processes and the script reads LOCAL_RANK; this is the recommended way for real jobs because it also gives multi-node support, restarts and elasticity.