.. role:: hidden
:class: hidden-section
Distributed communication package - torch.distributed
:::{note} Please refer to PyTorch Distributed Overview for a brief introduction to all features related to distributed training. :::
.. automodule:: torch.distributed
.. currentmodule:: torch.distributed
(distributed-backends)=
Backends
torch.distributed ships the following backends. Backends are registered
through the torch.distributed.backends entry point group and loaded on first use.
gloo: CPU and CUDA.nccl: CUDA.nccl-lazy: CUDA. Variant ofncclthat runs collectives on one communicator and creates a 2-rank communicator per point-to-point peer pair on first use.nccl-legacy: CUDA. The legacyProcessGroupNCCLimplementation.mpi: only when PyTorch is built with MPI.ucc: CPU and CUDA; only when PyTorch is built with UCC.xccl: Intel XPU.fake: no-op backend for testing.
The table below shows which functions are available for use with a CPU or GPU for four of these backends. For NCCL, GPU refers to CUDA GPU while for XCCL to XPU GPU.
MPI supports CUDA only if the implementation used to build PyTorch supports it.
+----------------+-----------+-----------+-----------+-----------+
| Backend | ``gloo`` | ``mpi`` | ``nccl`` | ``xccl`` |
+----------------+-----+-----+-----+-----+-----+-----+-----+-----+
| Device | CPU | GPU | CPU | GPU | CPU | GPU | CPU | GPU |
+================+=====+=====+=====+=====+=====+=====+=====+=====+
| send | ✓ | ✘ | ✓ | ? | ✘ | ✓ | ✘ | ✓ |
+----------------+-----+-----+-----+-----+-----+-----+-----+-----+
| recv | ✓ | ✘ | ✓ | ? | ✘ | ✓ | ✘ | ✓ |
+----------------+-----+-----+-----+-----+-----+-----+-----+-----+
| broadcast | ✓ | ✓ | ✓ | ? | ✘ | ✓ | ✘ | ✓ |
+----------------+-----+-----+-----+-----+-----+-----+-----+-----+
| all_reduce | ✓ | ✓ | ✓ | ? | ✘ | ✓ | ✘ | ✓ |
+----------------+-----+-----+-----+-----+-----+-----+-----+-----+
| reduce | ✓ | ✓ | ✓ | ? | ✘ | ✓ | ✘ | ✓ |
+----------------+-----+-----+-----+-----+-----+-----+-----+-----+
| all_gather | ✓ | ✓ | ✓ | ? | ✘ | ✓ | ✘ | ✓ |
+----------------+-----+-----+-----+-----+-----+-----+-----+-----+
| gather | ✓ | ✓ | ✓ | ? | ✘ | ✓ | ✘ | ✓ |
+----------------+-----+-----+-----+-----+-----+-----+-----+-----+
| scatter | ✓ | ✓ | ✓ | ? | ✘ | ✓ | ✘ | ✓ |
+----------------+-----+-----+-----+-----+-----+-----+-----+-----+
| reduce_scatter | ✓ | ✓ | ✘ | ✘ | ✘ | ✓ | ✘ | ✓ |
+----------------+-----+-----+-----+-----+-----+-----+-----+-----+
| all_to_all | ✘ | ✘ | ✓ | ? | ✘ | ✓ | ✘ | ✓ |
+----------------+-----+-----+-----+-----+-----+-----+-----+-----+
| barrier | ✓ | ✘ | ✓ | ? | ✘ | ✓ | ✘ | ✓ |
+----------------+-----+-----+-----+-----+-----+-----+-----+-----+
Backends that come with PyTorch
PyTorch distributed package supports Linux (stable), macOS (stable), and Windows (prototype). By default for Linux, the Gloo and NCCL backends are built and included in PyTorch distributed (NCCL only when building with CUDA). MPI is an optional backend that can only be included if you build PyTorch from source. (e.g. building PyTorch on a host that has MPI installed.)
:::{note}
As of PyTorch v1.8, Windows supports all collective communications backends but NCCL,
If the init_method argument of {func}init_process_group points to a file it must adhere
to the following schema:
- Local file system,
init_method="file:///d:/tmp/some_file" - Shared file system,
init_method="file://////{machine_name}/{share_folder_name}/some_file"
Same as on Linux platform, you can enable TcpStore by setting environment variables, MASTER_ADDR and MASTER_PORT. :::
Which backend to use?
In the past, we were often asked: "which backend should I use?".
-
Rule of thumb
- Use the NCCL backend for distributed training with CUDA GPU.
- Use the XCCL backend for distributed training with XPU GPU.
- Use the Gloo backend for distributed training with CPU.
-
GPU hosts with InfiniBand interconnect
- Use NCCL, since it's the only backend that currently supports InfiniBand and GPUDirect.
-
GPU hosts with Ethernet interconnect
- Use NCCL, since it currently provides the best distributed GPU training performance, especially for multiprocess single-node or multi-node distributed training. If you encounter any problem with NCCL, use Gloo as the fallback option. (Note that Gloo currently runs slower than NCCL for GPUs.)
-
CPU hosts with InfiniBand interconnect
- If your InfiniBand has enabled IP over IB, use Gloo, otherwise, use MPI instead. We are planning on adding InfiniBand support for Gloo in the upcoming releases.
-
CPU hosts with Ethernet interconnect
- Use Gloo, unless you have specific reasons to use MPI.
Common environment variables
Choosing the network interface to use
By default, both the NCCL and Gloo backends will try to find the right network interface to use. If the automatically detected interface is not correct, you can override it using the following environment variables (applicable to the respective backend):
- NCCL_SOCKET_IFNAME, for example
export NCCL_SOCKET_IFNAME=eth0 - GLOO_SOCKET_IFNAME, for example
export GLOO_SOCKET_IFNAME=eth0
If you're using the Gloo backend, you can specify multiple interfaces by separating
them by a comma, like this: export GLOO_SOCKET_IFNAME=eth0,eth1,eth2,eth3.
The backend will dispatch operations in a round-robin fashion across these interfaces.
It is imperative that all processes specify the same number of interfaces in this variable.
Other NCCL environment variables
Debugging - in case of NCCL failure, you can set NCCL_DEBUG=INFO to print an explicit
warning message as well as basic NCCL initialization information.
You may also use NCCL_DEBUG_SUBSYS to get more details about a specific
aspect of NCCL. For example, NCCL_DEBUG_SUBSYS=COLL would print logs of
collective calls, which may be helpful when debugging hangs, especially those
caused by collective type or message size mismatch. In case of topology
detection failure, it would be helpful to set NCCL_DEBUG_SUBSYS=GRAPH
to inspect the detailed detection result and save as reference if further help
from NCCL team is needed.
Performance tuning - NCCL performs automatic tuning based on its topology detection to save users'
tuning effort. On some socket-based systems, users may still try tuning
NCCL_SOCKET_NTHREADS and NCCL_NSOCKS_PERTHREAD to increase socket
network bandwidth. These two environment variables have been pre-tuned by NCCL
for some cloud providers, such as AWS or GCP.
For a full list of NCCL environment variables, please refer to NVIDIA NCCL's official documentation
You can tune NCCL communicators even further using torch.distributed.ProcessGroupNCCL.NCCLConfig,
set through the config attribute of torch.distributed.ProcessGroupNCCL.Options.
Pass the Options to {func}torch.distributed.init_process_group or
{func}torch.distributed.new_group as pg_options.
The same Options type is used by the nccl, nccl-lazy and nccl-legacy
backends. Learn more about them using help
(e.g. help(torch.distributed.ProcessGroupNCCL.NCCLConfig)) in the interpreter.
(nccl-collective-config)=
Per-collective NCCL configuration
The nccl and nccl-lazy backends accept a keyword-only config on supported collective functions. This requires NCCL 2.31 or later and
nccl4py 0.5.0 or later:
from nccl.core import NCCLCollConfig
import torch.distributed as dist
dist.init_process_group("nccl")
config = NCCLCollConfig(max_ctas=4, alg_selection="ring")
dist.all_reduce(tensor, config=config)
Supported functions: broadcast, all_reduce, all_reduce_coalesced, reduce,
all_gather, all_gather_single, all_gather_coalesced, gather_single,
reduce_scatter, reduce_scatter_single and all_to_all_single, plus the
back-compat aliases all_gather_into_tensor, gather_into_tensor and
reduce_scatter_tensor.
Unset fields inherit NCCL or communicator defaults; a config with no set fields
is treated as None. Config presence and values must be identical on every
participating rank; mismatches can hang. Configurations within an NCCL group must
agree on cga_cluster_size. Passing None preserves existing behavior and does
not require nccl4py.
Backends receive config as its attribute dictionary (vars(config)); a plain
dict with the same keys is equivalent. nccl-legacy, gloo and the other built-in backends ignore it.
nccl rejects vendor options and unsupported operations. all_to_all_single
with a config requires even splits on every rank. External NCCL group scopes are unsupported.
Supported synchronous calls can use torch.compile and torch.export.
Configuration values are graph constants; changing them recompiles.
(distributed-basics)=
Basics
The torch.distributed package provides PyTorch support and communication primitives
for multiprocess parallelism across several computation nodes running on one or more
machines. The class {func}torch.nn.parallel.DistributedDataParallel builds on this
functionality to provide synchronous distributed training as a wrapper around any
PyTorch model. This differs from the kinds of parallelism provided by
{doc}multiprocessing and {func}torch.nn.DataParallel in that it supports
multiple network-connected machines and in that the user must explicitly launch a separate
copy of the main training script for each process.
In the single-machine synchronous case, torch.distributed or the
{func}torch.nn.parallel.DistributedDataParallel wrapper may still have advantages over other
approaches to data-parallelism, including {func}torch.nn.DataParallel:
- Each process maintains its own optimizer and performs a complete optimization step with each iteration. While this may appear redundant, since the gradients have already been gathered together and averaged across processes and are thus the same for every process, this means that no parameter broadcast step is needed, reducing time spent transferring tensors between nodes.
- Each process contains an independent Python interpreter, eliminating the extra interpreter overhead and "GIL-thrashing" that comes from driving several execution threads, model replicas, or GPUs from a single Python process. This is especially important for models that make heavy use of the Python runtime, including models with recurrent layers or many small components.
Initialization
The package needs to be initialized using the {func}torch.distributed.init_process_group
or {func}torch.distributed.device_mesh.init_device_mesh function before calling any other methods.
Both block until all processes have joined.
:::{warning} Initialization is not thread-safe. Process group creation should be performed from a single thread, to prevent inconsistent 'UUID' assignment across ranks, and to prevent races during initialization that can lead to hangs. :::
.. autofunction:: is_available
.. autofunction:: init_process_group
.. autofunction:: torch.distributed.device_mesh.init_device_mesh
.. autofunction:: is_initialized
.. autofunction:: is_mpi_available
.. autofunction:: is_nccl_available
.. autofunction:: is_gloo_available
.. autofunction:: torch.distributed.distributed_c10d.is_xccl_available
.. autofunction:: torch.distributed.distributed_c10d.batch_isend_irecv
.. autofunction:: torch.distributed.distributed_c10d.destroy_process_group
.. autofunction:: torch.distributed.distributed_c10d.is_backend_available
.. autofunction:: torch.distributed.distributed_c10d.irecv
.. autofunction:: torch.distributed.distributed_c10d.is_gloo_available
.. autofunction:: torch.distributed.distributed_c10d.is_initialized
.. autofunction:: torch.distributed.distributed_c10d.is_mpi_available
.. autofunction:: torch.distributed.distributed_c10d.is_nccl_available
.. autofunction:: torch.distributed.distributed_c10d.is_torchelastic_launched
.. autofunction:: torch.distributed.distributed_c10d.is_ucc_available
.. autofunction:: is_torchelastic_launched
.. autofunction:: get_default_backend_for_device
Currently three initialization methods are supported:
TCP initialization
There are two ways to initialize using TCP, both requiring a network address
reachable from all processes and a desired world_size. The first way
requires specifying an address that belongs to the rank 0 process. This
initialization method requires that all processes have manually specified ranks.
Note that multicast address is not supported anymore in the latest distributed
package. group_name is deprecated as well.
import torch.distributed as dist
# Use address of one of the machines
dist.init_process_group(backend, init_method='tcp://10.1.1.20:23456',
rank=args.rank, world_size=4)
Shared file-system initialization
Another initialization method makes use of a file system that is shared and
visible from all machines in a group, along with a desired world_size. The URL should start
with file:// and contain a path to a non-existent file (in an existing
directory) on a shared file system. File-system initialization will automatically
create that file if it doesn't exist, but will not delete the file. Therefore, it
is your responsibility to make sure that the file is cleaned up before the next
{func}init_process_group call on the same file path/name.
Note that automatic rank assignment is not supported anymore in the latest
distributed package and group_name is deprecated as well.
:::{warning}
This method assumes that the file system supports locking using fcntl - most
local systems and NFS support it.
:::
:::{warning}
This method will always create the file and try its best to clean up and remove
the file at the end of the program. In other words, each initialization with
the file init method will need a brand new empty file in order for the initialization
to succeed. If the same file used by the previous initialization (which happens not
to get cleaned up) is used again, this is unexpected behavior and can often cause
deadlocks and failures. Therefore, even though this method will try its best to clean up
the file, if the auto-delete happens to be unsuccessful, it is your responsibility
to ensure that the file is removed at the end of the training to prevent the same
file to be reused again during the next time. This is especially important
if you plan to call {func}init_process_group multiple times on the same file name.
In other words, if the file is not removed/cleaned up and you call
{func}init_process_group again on that file, failures are expected.
The rule of thumb here is that, make sure that the file is non-existent or
empty every time {func}init_process_group is called.
:::
import torch.distributed as dist
# rank should always be specified
dist.init_process_group(backend, init_method='file:///mnt/nfs/sharedfile',
world_size=4, rank=args.rank)
Environment variable initialization
This method will read the configuration from environment variables, allowing one to fully customize how the information is obtained. The variables to be set are:
MASTER_PORT- required; has to be a free port on machine with rank 0MASTER_ADDR- required (except for rank 0); address of rank 0 nodeWORLD_SIZE- required; can be set either here, or in a call to init functionRANK- required; can be set either here, or in a call to init function
The machine with rank 0 will be used to set up all connections.
This is the default method, meaning that init_method does not have to be specified (or
can be env://).
Custom initialization methods
Other init_method URL schemes can be added by registering a rendezvous handler.
.. autofunction:: torch.distributed.rendezvous.register_rendezvous_handler
Improving initialization time
TORCH_GLOO_LAZY_INIT- establishes connections on demand rather than using a full mesh which can greatly improve initialization time for non all2all operations.
Post-Initialization
Once {func}torch.distributed.init_process_group was run, the following functions can be used. To
check whether the process group has already been initialized use {func}torch.distributed.is_initialized.
.. autoclass:: Backend
:members:
.. autofunction:: get_backend
.. autofunction:: get_backend_impl
.. autofunction:: get_backend_config
.. autofunction:: get_rank
.. autofunction:: get_world_size
.. autofunction:: get_debug_level
.. autofunction:: set_debug_level
.. autofunction:: set_debug_level_from_env
.. autoclass:: DebugLevel
.. autofunction:: get_node_local_rank
.. autofunction:: get_pg_count
.. autofunction:: set_timeout
Experimental collective time estimation
The context manager and the backend's _supports_time_estimate capability probe are
experimental and may change without notice.
.. autofunction:: torch.distributed.distributed_c10d._time_estimator
Fault-tolerant reconfiguration
.. autofunction:: torch.distributed.distributed_c10d._supports_reconfigure
.. autofunction:: torch.distributed.distributed_c10d._get_reconfigure_handle
.. autofunction:: torch.distributed.distributed_c10d._reconfigure
Shutdown
It is important to clean up resources on exit by calling {func}destroy_process_group.
The simplest pattern to follow is to destroy every process group and backend by calling
{func}destroy_process_group() with the default value of None for the group argument, at a
point in the training script where communications are no longer needed, usually near the
end of main(). The call should be made once per trainer-process, not at the outer
process-launcher level.
if {func}destroy_process_group is not called by all ranks in a pg within the timeout duration,
especially when there are multiple process-groups in the application e.g. for N-D parallelism,
hangs on exit are possible. This is because the NCCL backends call ncclCommAbort in their destructor if the group was not shut down,
which must be called collectively, but the order of calling the destructors if called
by python's GC is not deterministic. Calling {func}destroy_process_group helps by ensuring
communicators are torn down in a consistent order across ranks, and avoids calling ncclCommAbort
during the destructor.
Reinitialization
destroy_process_group can also be used to destroy individual process groups. One use
case could be fault tolerant training, where a process group may be destroyed and then
a new one initialized during runtime. In this case, it's critical to synchronize the trainer
processes using some means other than torch.distributed primitives _after_ calling destroy and
before subsequently initializing. This behavior is currently unsupported/untested, due to
the difficulty of achieving this synchronization, and is considered a known issue. Please file
a github issue or RFC if this is a use case that's blocking you.
Groups
By default collectives operate on the default group (also called the world) and
require all processes to enter the distributed function call. However, some workloads can benefit
from more fine-grained communication. This is where distributed groups come
into play. {func}~torch.distributed.new_group function can be
used to create new groups, with arbitrary subsets of all processes. It returns
an opaque group handle that can be given as a group argument to all collectives
(collectives are distributed functions to exchange information in certain well-known programming patterns).
.. autoclass:: ProcessGroup
.. autoclass:: group
.. autofunction:: new_group
.. autofunction:: new_subgroups
.. autofunction:: new_subgroups_by_enumeration
.. autofunction:: torch.distributed.distributed_c10d.shrink_group
.. autofunction:: get_group_rank
.. autofunction:: get_global_rank
.. autofunction:: get_process_group_ranks
.. autofunction:: split_group
.. autodata:: torch.distributed.distributed_c10d.GroupName
DeviceMesh
DeviceMesh is a higher level abstraction that manages process groups (or NCCL communicators).
It allows user to easily create inter node and intra node process groups without worrying about
how to set up the ranks correctly for different sub process groups, and it helps manage those
distributed process group easily. {func}~torch.distributed.device_mesh.init_device_mesh function can be
used to create new DeviceMesh, with a mesh shape describing the device topology.
.. autoclass:: torch.distributed.device_mesh.DeviceMesh
:members:
Point-to-point communication
.. autofunction:: send
.. autofunction:: recv
{func}~torch.distributed.isend and {func}~torch.distributed.irecv
return distributed request objects when used. In general, the type of this object is unspecified
as they should never be created manually, but they are guaranteed to support two methods:
is_completed()- returns True if the operation has finishedwait()- will block the process until the operation is finished.is_completed()is guaranteed to return True once it returns.
.. autofunction:: isend
.. autofunction:: irecv
.. autofunction:: send_object_list
.. autofunction:: recv_object_list
.. autofunction:: batch_isend_irecv
.. autoclass:: P2POp
(distributed-one-sided)=
One-sided communication (experimental)
The window API is experimental and may change without notice.
A window exposes a tensor on every rank of a group for one-sided (RMA) writes:
a rank can write into a peer's tensor with {meth}~torch.distributed.distributed_c10d.Window.put without the peer
posting a matching receive. Peers synchronize with {meth}~torch.distributed.distributed_c10d.Window.signal and
{meth}~torch.distributed.distributed_c10d.Window.wait_signal. The nccl and nccl-lazy backends support
windows when PyTorch is built against, and runs with, NCCL 2.29 or later. nccl-legacy does not, nor does nccl
when TORCH_DIST_USE_NCCL2=0 selects the legacy implementation.
{func}~torch.distributed.distributed_c10d._supports_window only checks the backend and NCCL version:
registration can still fail if no transport between the ranks supports
symmetric memory (e.g. no NVLink or InfiniBand).
With nccl and nccl-lazy:
- Memory. The window tensor must be contiguous and allocated from the
backend's memory pool,
torch.cuda.MemPool(backend.mem_allocator). Registration covers the tensor's whole allocator segment, so all ranks must register matching segments; allocating the same sizes in the same order on every rank satisfies this. - Put sources. The source of {meth}
~torch.distributed.distributed_c10d.Window.putmust be contiguous and lie in an allocator segment that has a window on the same process group, e.g. a slice of this window's tensor.backend.register_mem_pool(pool, symm=True)gives every segment the pool allocates afterwards a symmetric window, so any tensor allocated from the pool after the call is a valid source. Each new segment is then registered collectively, so all ranks must allocate the same sizes in the same order, and allocation raises if no transport supports symmetric memory. Segments that already exist are upgraded too, but without such a transport they only log a warning and are not valid sources. - Registration. A window holds one tensor at a time; call
{meth}
~torch.distributed.distributed_c10d.Window.tensor_deregisterbefore registering another. {func}~torch.distributed.distributed_c10d._new_windowwith a tensor already registers it. - Signals. Each {meth}
~torch.distributed.distributed_c10d.Window.putalso signals the destination rank; see {meth}~torch.distributed.distributed_c10d.Window.wait_signalfor how signals are counted. - Teardown. {meth}
~torch.distributed.distributed_c10d.Window.tensor_deregisteronly drops the window's bookkeeping; the segment stays registered with NCCL until the allocator frees it, and every rank must free its segments in the same order or teardown can hang. To avoid this, register the pool withbackend.register_mem_pool(eithersymmvalue) and tear down in this order on every rank: synchronize outstanding window work, calltensor_deregisteron every window backed by the pool, callbackend.deregister_mem_pool(pool), free the tensors and pool, then call {func}~torch.distributed.distributed_c10d.destroy_process_group. Deregistering the pool tears down its segment windows immediately, so windows backed by it must not be used afterwards. - Limitations. {meth}
~torch.distributed.distributed_c10d.Window.map_remote_tensoronly supports the local rank and requires the defaultowning=Trueregistration, and {meth}~torch.distributed.distributed_c10d.Window.get_attralways reportsSEPARATE.
The example below runs a ring: each rank writes its slice into the next rank's window and waits for the previous rank's slice to arrive in its own. The source is the last slot of the registered buffer.
import os
import torch
import torch.distributed as dist
local_rank = int(os.environ["LOCAL_RANK"])
device = torch.device("cuda", local_rank)
# MemPool and use_mem_pool use the current device.
torch.cuda.set_device(device)
dist.init_process_group("nccl", device_id=device)
rank, world_size = dist.get_rank(), dist.get_world_size()
assert dist._supports_window()
backend = dist.get_backend_impl(device=device)
pool = torch.cuda.MemPool(backend.mem_allocator)
# Each segment later allocated from the pool becomes a symmetric window.
backend.register_mem_pool(pool, symm=True)
count = 1024
with torch.cuda.use_mem_pool(pool):
# Collective: a new segment is registered on every rank, so all ranks must
# allocate the same sizes in the same order.
# One slot per rank plus a trailing slot used as the put source.
buf = torch.zeros(count * (world_size + 1), dtype=torch.float, device=device)
# Collective: every rank registers its buffer.
win = dist._new_window(buf)
src = buf[world_size * count :]
src.fill_(rank)
next_rank = (rank + 1) % world_size
prev_rank = (rank - 1) % world_size
# Write src into slot `rank` of the next rank's buffer and signal it.
win.put(src, next_rank, rank * count, async_op=False)
# Wait until the previous rank's put has landed in this rank's buffer.
win.wait_signal(prev_rank, async_op=False)
torch.cuda.synchronize()
assert buf[prev_rank * count : (prev_rank + 1) * count].eq(prev_rank).all()
# Collective, stream-ordered (does not block the host).
win.tensor_deregister()
# Collective: tear down the segments' NCCL windows before freeing them.
backend.deregister_mem_pool(pool)
del win, src, buf, pool
dist.destroy_process_group()
{meth}~torch.distributed.distributed_c10d.Window.put, {meth}~torch.distributed.distributed_c10d.Window.signal and
{meth}~torch.distributed.distributed_c10d.Window.wait_signal return a Work handle. With nccl and
nccl-lazy, async_op=False enqueues the operation on the current stream;
async_op=True enqueues it on an internal stream ordered after the current
stream, and Work.wait() makes the current stream wait for it.
.. autofunction:: torch.distributed.distributed_c10d._supports_window
.. autofunction:: torch.distributed.distributed_c10d._new_window
.. autoclass:: torch.distributed.distributed_c10d.Window
:members:
.. autoclass:: torch.distributed.distributed_c10d.PutOptions
:members:
.. autoclass:: torch.distributed.distributed_c10d.SignalOptions
:members:
.. autoclass:: torch.distributed.distributed_c10d.WaitSignalOptions
:members:
.. autoclass:: torch.distributed.distributed_c10d.WindowAttr
:members:
.. autoclass:: torch.distributed.distributed_c10d.WindowAccessType
Synchronous and asynchronous collective operations
Every collective operation function supports the following two kinds of operations,
depending on the setting of the async_op flag passed into the collective:
Synchronous operation - the default mode, when async_op is set to False.
When the function returns, it is guaranteed that
the collective operation is performed. In the case of CUDA operations, it is not guaranteed
that the CUDA operation is completed, since CUDA operations are asynchronous. For CPU collectives, any
further function calls utilizing the output of the collective call will behave as expected. For CUDA collectives,
function calls utilizing the output on the same CUDA stream will behave as expected. Users must take care of
synchronization under the scenario of running under different streams. For details on CUDA semantics such as stream
synchronization, see CUDA Semantics.
See the below script to see examples of differences in these semantics for CPU and CUDA operations.
Asynchronous operation - when async_op is set to True. The collective operation function
returns a distributed request object. In general, you don't need to create it manually and it
is guaranteed to support two methods:
is_completed()- in the case of CPU collectives, returnsTrueif completed. In the case of CUDA operations, returnsTrueif the operation has been successfully enqueued onto a CUDA stream and the output can be utilized on the default stream without further synchronization.wait()- in the case of CPU collectives, will block the process until the operation is completed. In the case of CUDA collectives, will block the currently active CUDA stream until the operation is completed (but will not block the CPU).get_future()- returnstorch._C.Futureobject. Supported for NCCL, also supported for most operations on GLOO and MPI, except for peer to peer operations. Note: as we continue adopting Futures and merging APIs,get_future()call might become redundant.
Example
The following code can serve as a reference regarding semantics for CUDA operations when using distributed collectives. It shows the explicit need to synchronize when using collective outputs on different CUDA streams:
# Code runs on each rank.
dist.init_process_group("nccl", rank=rank, world_size=2)
output = torch.tensor([rank]).cuda(rank)
s = torch.cuda.Stream()
handle = dist.all_reduce(output, async_op=True)
# Wait ensures the operation is enqueued, but not necessarily complete.
handle.wait()
# Using result on non-default stream.
with torch.cuda.stream(s):
s.wait_stream(torch.cuda.default_stream())
output.add_(100)
if rank == 0:
# if the explicit call to wait_stream was omitted, the output below will be
# non-deterministically 1 or 101, depending on whether the allreduce overwrote
# the value after the add completed.
print(output)
Collective functions
.. autofunction:: broadcast
.. autofunction:: broadcast_object_list
.. autofunction:: all_reduce
.. autofunction:: all_reduce_coalesced
.. autofunction:: reduce
.. autofunction:: all_gather
.. autofunction:: all_gather_single
.. autofunction:: all_gather_object
.. autofunction:: all_gather_coalesced
.. autofunction:: gather
.. autofunction:: gather_single
.. autofunction:: gather_object
.. autofunction:: scatter
.. autofunction:: scatter_object_list
.. autofunction:: reduce_scatter
.. autofunction:: reduce_scatter_single
.. autofunction:: all_to_all_single
.. autofunction:: all_to_all
.. autofunction:: barrier
.. autofunction:: monitored_barrier
.. autoclass:: Work
:members:
.. autoclass:: ReduceOp
:members:
.. class:: reduce_op
Deprecated enum-like class for reduction operations: ``SUM``, ``PRODUCT``,
``MIN``, and ``MAX``.
:class:`~torch.distributed.ReduceOp` is recommended to use instead.
Functional collectives
Functional collectives return new tensors instead of mutating their inputs and are traceable by torch.compile. See {doc}distributed/functional_collectives.
Distributed Key-Value Store
The distributed package comes with a distributed key-value store, which can be
used to share information between processes in the group as well as to
initialize the distributed package in
{func}torch.distributed.init_process_group (by explicitly creating the store
as an alternative to specifying init_method.) There are 3 choices for
Key-Value Stores: {class}~torch.distributed.TCPStore,
{class}~torch.distributed.FileStore, and {class}~torch.distributed.HashStore.
.. autoclass:: Store
:members:
:special-members:
.. autoclass:: TCPStore
:members:
:special-members: __init__
.. autoclass:: HashStore
:members:
:special-members: __init__
.. autoclass:: FileStore
:members:
:special-members: __init__
.. autoclass:: PrefixStore
:members:
:special-members: __init__
Profiling Collective Communication
Note that you can use torch.profiler (recommended, only available after 1.8.1) or torch.autograd.profiler to profile collective communication and point-to-point communication APIs mentioned here. All out-of-the-box backends (gloo,
nccl, mpi) are supported and collective communication usage will be rendered as expected in profiling output/traces. Profiling your code is the same as any regular torch operator:
import torch
import torch.distributed as dist
with torch.profiler():
tensor = torch.randn(20, 10)
dist.all_reduce(tensor)
Please refer to the profiler documentation for a full overview of profiler features.
.. autofunction:: torch.distributed.distributed_c10d.record_comm
Hooks
Process groups can run callbacks around the operations issued through them, for monitoring and debugging.
{meth}ProcessGroup.register_pre_hook <torch.distributed.ProcessGroup.register_pre_hook>
and {meth}ProcessGroup.register_post_hook <torch.distributed.ProcessGroup.register_post_hook>
register hooks that run before and after each operation is issued, for every
backend. A post-hook runs once the operation is issued, not when it completes.
op_id pairs a pre-hook call with its post-hook call. Hooks run for the
standard collective and point-to-point operations, and with no tensors for
{func}torch.distributed.split_group and the ProcessGroup methods
new_window and reconfigure (op names SPLIT, NEW_WINDOW and
RECONFIGURE). The SPLIT and NEW_WINDOW post-hooks get work=None and the
new group or window. The SPLIT post-hook runs before
{func}torch.distributed.split_group registers the group, so lookups such as
get_rank(group) or get_process_group_ranks fail on it inside the hook.
Other synchronous operations may also pass work=None, so hooks must not
assume a Work or non-empty tensor lists. Calling the Backend methods
split, new_window or reconfigure directly, or a Python subclass override
of the ProcessGroup methods, bypasses hooks. Other group creation paths, such
as new_group (including when it splits from an eagerly initialized default
group), {func}torch.distributed.distributed_c10d.shrink_group and
ProcessGroup.merge_remote_group, fire no hooks.
The example below assumes the default process group is initialized.
import torch
import torch.distributed as dist
from torch.distributed.distributed_c10d import HookOpName
pg = dist.group.WORLD
def pre_hook(args):
if args.name == HookOpName.ALLREDUCE:
print(f"all_reduce {args.op_id}: {[t.shape for t in args.input_tensors]}")
pg.register_pre_hook(0, pre_hook)
dist.all_reduce(torch.ones(4))
pg.unregister_pre_hook(0)
{meth}ProcessGroup.register_abort_hook <torch.distributed.ProcessGroup.register_abort_hook>
registers a hook that runs when the backend detects a timeout or error, before it
aborts; it does not run on a user-requested abort or shutdown. Check
{attr}~torch.distributed.ProcessGroup.supports_abort_hooks first.
PyTorch attaches these built-in hooks to new process groups:
- {class}
~torch.distributed.distributed_c10d.FlightRecorderHookrecords operations into the flight recorder for backends without native recording. Disabled byTORCH_FR_BUFFER_SIZE=0. - {class}
~torch.distributed.distributed_c10d.NanCheckHookchecks operation inputs for NaNs. Enabled byTORCH_DIST_NAN_CHECK=1. - {class}
~torch.distributed.distributed_c10d.HealthCheckHookreports aborted backends through the/c10d_health_checkdebug server endpoint.
.. automethod:: torch.distributed.ProcessGroup.register_pre_hook
.. automethod:: torch.distributed.ProcessGroup.unregister_pre_hook
.. automethod:: torch.distributed.ProcessGroup.register_post_hook
.. automethod:: torch.distributed.ProcessGroup.unregister_post_hook
.. autoattribute:: torch.distributed.ProcessGroup.supports_abort_hooks
.. automethod:: torch.distributed.ProcessGroup.register_abort_hook
.. automethod:: torch.distributed.ProcessGroup.unregister_abort_hook
.. autoclass:: torch.distributed.distributed_c10d.PreHookArgs
:members:
.. autoclass:: torch.distributed.distributed_c10d.PostHookArgs
:members:
.. autoclass:: torch.distributed.distributed_c10d.HookOpName
:members:
.. autoclass:: torch.distributed.distributed_c10d.FlightRecorderHook
:members:
.. autoclass:: torch.distributed.distributed_c10d.NanCheckHook
:members:
.. autoclass:: torch.distributed.distributed_c10d.HealthCheckHook
:members:
Optimization with Symmetric Memory
NCCL Symmetric Kernels
NCCL 2.27 and later ship device kernels written specifically for symmetric,
window-registered buffers, using low-latency, multimem/NVLS, and TMA algorithms
rather than the generic ring/tree path. all_reduce, all_gather_single
and reduce_scatter_single dispatch to them automatically once their buffers
are registered — the call site does not change. When the buffers are not
registered, or the op/dtype combination has no symmetric implementation, NCCL
silently falls back to the regular path.
For how to register buffers, the supported op/dtype matrix, and how to confirm the symmetric kernels actually ran, see NCCL Symmetric Kernels in the Symmetric Memory documentation.
Copy Engine Collectives
When NCCL collective operations are performed on symmetric memory tensors with the zero-CTA policy, data movement is offloaded to the GPU's copy engines (DMA engines) instead of using CUDA streaming multiprocessors (SMs). This frees up SMs for compute work, enabling better overlap of communication and computation.
For setup instructions, requirements, and examples, see Copy Engine Collectives in the Symmetric Memory documentation.
Higher-Precision Reduction
When NCCL collectives such as reduce_scatter and all_reduce operate on
symmetric memory tensors, NCCL's symmetric kernel implementation automatically
performs internal reduction with higher precision (e.g., BF16/FP16 in → FP32
accumulate → BF16/FP16 out). This improves numerical accuracy without any code
changes to the collective call.
For details on scope, supported domains, and version requirements, see Higher-Precision Reduction in the Symmetric Memory documentation.
(object_collectives)=
Object collectives
:::{warning} Object collectives have a number of serious limitations. Read further to determine if they are safe to use for your use case. :::
Object collectives are a set of collective-like operations that work on arbitrary Python objects, as long as they can be pickled. There are various collective patterns implemented (e.g. broadcast, all_gather, ...) but they each roughly follow this pattern:
- convert the input object into a pickle (raw bytes), then shove it into a byte tensor
- communicate the size of this byte tensor to peers (first collective operation)
- allocate appropriately sized tensor to perform the real collective
- communicate the object data (second collective operation)
- convert raw data back into Python (unpickle)
Object collectives sometimes have surprising performance or memory characteristics that lead to long runtimes or OOMs, and thus they should be used with caution. Here are some common issues.
Asymmetric pickle/unpickle time - Pickling objects can be slow, depending on the number, type and size of the objects. When the collective has a fan-in (e.g. gather_object), the receiving rank(s) must unpickle N times more objects than the sending rank(s) had to pickle, which can cause other ranks to time out on their next collective.
Inefficient tensor communication - Tensors should be sent via regular collective APIs, not object collective APIs. It is possible to send Tensors via object collective APIs, but they will be serialized and deserialized (including a CPU-sync and device-to-host copy in the case of non-CPU tensors), and in almost every case other than debugging or troubleshooting code, it would be worth the trouble to refactor the code to use non-object collectives instead.
Unexpected tensor devices - If you still want to send tensors via object collectives, there is another aspect
specific to cuda (and possibly other accelerators) tensors. If you pickle a tensor that is currently on cuda:3, and
then unpickle it, you will get another tensor on cuda:3 regardless of which process you are on, or which CUDA device
is the 'default' device for that process. With regular tensor collective APIs, 'output tensors' will always be on the
same, local device, which is generally what you'd expect.
Unpickling a tensor will implicitly activate a CUDA context if it is the first time a GPU is used by the process, which can waste significant amounts of GPU memory. This issue can be avoided by moving tensors to CPU before passing them as inputs to an object collective.
Custom backends
Besides the built-in backends listed under Backends, torch.distributed supports
backends registered at run time, written in C++ or Python. See
{doc}distributed/custom_backends.
(distributed-launch)=
Launch utility
The torch.distributed package also provides a launch utility in
torch.distributed.launch. This helper utility can be used to launch
multiple processes per node for distributed training.
.. automodule:: torch.distributed.launch
.. currentmodule:: torch.distributed.launch
.. autofunction:: launch
.. autofunction:: main
.. autofunction:: parse_args
Spawn utility
The {ref}multiprocessing-doc package also provides a spawn
function in {func}torch.multiprocessing.spawn. This helper function
can be used to spawn multiple processes. It works by passing in the
function that you want to run and spawns N processes to run it. This
can be used for multiprocess distributed training as well.
For references on how to use it, please refer to PyTorch example - ImageNet implementation
Debugging torch.distributed applications
Debugging distributed applications can be challenging due to hard to understand hangs, crashes, or inconsistent behavior across ranks. torch.distributed provides
a suite of tools to help debug training applications in a self-serve fashion:
Python Breakpoint
It is extremely convenient to use python's debugger in a distributed environment, but because it does not work out of the box many people do not use it at all. PyTorch offers a customized wrapper around pdb that streamlines the process.
torch.distributed.breakpoint makes this process easy. Internally, it customizes pdb's breakpoint behavior in three ways but otherwise behaves as normal pdb.
- Attaches the debugger only on one rank (specified by the user).
- Ensures all other ranks stop, by using a
torch.distributed.barrier()that will release once the debugged rank issues acontinue - Reroutes stdin from the child process such that it connects to your terminal.
To use it, simply issue torch.distributed.breakpoint(rank) on all ranks, using the same value for rank in each case.
Monitored Barrier
As of v1.10, {func}torch.distributed.monitored_barrier exists as an alternative to {func}torch.distributed.barrier which fails with helpful information about which rank may be faulty
when crashing, i.e. not all ranks calling into {func}torch.distributed.monitored_barrier within the provided timeout. {func}torch.distributed.monitored_barrier implements a host-side
barrier using send/recv communication primitives in a process similar to acknowledgements, allowing rank 0 to report which rank(s) failed to acknowledge
the barrier in time. As an example, consider the following function where rank 1 fails to call into {func}torch.distributed.monitored_barrier (in practice this could be due
to an application bug or hang in a previous collective):
import os
from datetime import timedelta
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
def worker(rank):
dist.init_process_group("nccl", rank=rank, world_size=2)
# monitored barrier requires gloo process group to perform host-side sync.
group_gloo = dist.new_group(backend="gloo")
if rank not in [1]:
dist.monitored_barrier(group=group_gloo, timeout=timedelta(seconds=2))
if __name__ == "__main__":
os.environ["MASTER_ADDR"] = "localhost"
os.environ["MASTER_PORT"] = "29501"
mp.spawn(worker, nprocs=2, args=())
The following error message is produced on rank 0, allowing the user to determine which rank(s) may be faulty and investigate further:
RuntimeError: Rank 1 failed to pass monitoredBarrier in 2000 ms
Original exception:
[gloo/transport/tcp/pair.cc:598] Connection closed by peer [2401:db00:eef0:1100:3560:0:1c05:25d]:8594
TORCH_DISTRIBUTED_DEBUG
With TORCH_CPP_LOG_LEVEL=INFO, the environment variable TORCH_DISTRIBUTED_DEBUG can be used to trigger additional useful logging and collective synchronization checks to ensure all ranks
are synchronized appropriately. TORCH_DISTRIBUTED_DEBUG can be set to either OFF (default), INFO, or DETAIL depending on the debugging level
required. Please note that the most verbose option, DETAIL may impact the application performance and thus should only be used when debugging issues.
Setting TORCH_DISTRIBUTED_DEBUG=INFO will result in additional debug logging when models trained with {func}torch.nn.parallel.DistributedDataParallel are initialized, and
TORCH_DISTRIBUTED_DEBUG=DETAIL will additionally log runtime performance statistics a select number of iterations. These runtime statistics
include data such as forward time, backward time, gradient communication time, etc. As an example, given the following application:
import os
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
class TwoLinLayerNet(torch.nn.Module):
def __init__(self):
super().__init__()
self.a = torch.nn.Linear(10, 10, bias=False)
self.b = torch.nn.Linear(10, 1, bias=False)
def forward(self, x):
a = self.a(x)
b = self.b(x)
return (a, b)
def worker(rank):
dist.init_process_group("nccl", rank=rank, world_size=2)
torch.cuda.set_device(rank)
print("init model")
model = TwoLinLayerNet().cuda()
print("init ddp")
ddp_model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[rank])
inp = torch.randn(10, 10).cuda()
print("train")
for _ in range(20):
output = ddp_model(inp)
loss = output[0] + output[1]
loss.sum().backward()
if __name__ == "__main__":
os.environ["MASTER_ADDR"] = "localhost"
os.environ["MASTER_PORT"] = "29501"
os.environ["TORCH_CPP_LOG_LEVEL"]="INFO"
os.environ[
"TORCH_DISTRIBUTED_DEBUG"
] = "DETAIL" # set to DETAIL for runtime logging.
mp.spawn(worker, nprocs=2, args=())
The following logs are rendered at initialization time:
I0607 16:10:35.739390 515217 logger.cpp:173] [Rank 0]: DDP Initialized with:
broadcast_buffers: 1
bucket_cap_bytes: 26214400
find_unused_parameters: 0
gradient_as_bucket_view: 0
is_multi_device_module: 0
iteration: 0
num_parameter_tensors: 2
output_device: 0
rank: 0
total_parameter_size_bytes: 440
world_size: 2
backend_name: nccl
bucket_sizes: 440
cuda_visible_devices: N/A
device_ids: 0
dtypes: float
master_addr: localhost
master_port: 29501
module_name: TwoLinLayerNet
nccl_async_error_handling: N/A
nccl_blocking_wait: N/A
nccl_debug: WARN
nccl_ib_timeout: N/A
nccl_nthreads: N/A
nccl_socket_ifname: N/A
torch_distributed_debug: INFO
The following logs are rendered during runtime (when TORCH_DISTRIBUTED_DEBUG=DETAIL is set):
I0607 16:18:58.085681 544067 logger.cpp:344] [Rank 1 / 2] Training TwoLinLayerNet unused_parameter_size=0
Avg forward compute time: 40838608
Avg backward compute time: 5983335
Avg backward comm. time: 4326421
Avg backward comm/comp overlap time: 4207652
I0607 16:18:58.085693 544066 logger.cpp:344] [Rank 0 / 2] Training TwoLinLayerNet unused_parameter_size=0
Avg forward compute time: 42850427
Avg backward compute time: 3885553
Avg backward comm. time: 2357981
Avg backward comm/comp overlap time: 2234674
In addition, TORCH_DISTRIBUTED_DEBUG=INFO enhances crash logging in {func}torch.nn.parallel.DistributedDataParallel due to unused parameters in the model. Currently, find_unused_parameters=True
must be passed into {func}torch.nn.parallel.DistributedDataParallel initialization if there are parameters that may be unused in the forward pass, and as of v1.10, all model outputs are required
to be used in loss computation as {func}torch.nn.parallel.DistributedDataParallel does not support unused parameters in the backwards pass. These constraints are challenging especially for larger
models, thus when crashing with an error, {func}torch.nn.parallel.DistributedDataParallel will log the fully qualified name of all parameters that went unused. For example, in the above application,
if we modify loss to be instead computed as loss = output[1], then TwoLinLayerNet.a does not receive a gradient in the backwards pass, and
thus results in DDP failing. On a crash, the user is passed information about parameters which went unused, which may be challenging to manually find for large models:
RuntimeError: Expected to have finished reduction in the prior iteration before starting a new one. This error indicates that your module has parameters that were not used in producing loss. You can enable unused parameter detection by passing
the keyword argument `find_unused_parameters=True` to `torch.nn.parallel.DistributedDataParallel`, and by
making sure all `forward` function outputs participate in calculating loss.
If you already have done the above, then the distributed data parallel module wasn't able to locate the output tensors in the return value of your module's `forward` function. Please include the loss function and the structure of the return va
lue of `forward` of your module when reporting this issue (e.g. list, dict, iterable).
Parameters which did not receive grad for rank 0: a.weight
Parameter indices which did not receive grad for rank 0: 0
Setting TORCH_DISTRIBUTED_DEBUG=DETAIL will trigger additional consistency and synchronization checks on every collective call issued by the user
either directly or indirectly (such as DDP allreduce). This is done by creating a wrapper process group that wraps all process groups returned by
{func}torch.distributed.init_process_group and {func}torch.distributed.new_group APIs. As a result, these APIs will return a wrapper process group that can be used exactly like a regular process
group, but performs consistency checks before dispatching the collective to an underlying process group. Currently, these checks include a {func}torch.distributed.monitored_barrier,
which ensures all ranks complete their outstanding collective calls and reports ranks which are stuck. Next, the collective itself is checked for consistency by
ensuring all collective functions match and are called with consistent tensor shapes. If this is not the case, a detailed error report is included when the
application crashes, rather than a hang or uninformative error message. As an example, consider the following function which has mismatched input shapes into
{func}torch.distributed.all_reduce:
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
def worker(rank):
dist.init_process_group("nccl", rank=rank, world_size=2)
torch.cuda.set_device(rank)
tensor = torch.randn(10 if rank == 0 else 20).cuda()
dist.all_reduce(tensor)
torch.cuda.synchronize(device=rank)
if __name__ == "__main__":
os.environ["MASTER_ADDR"] = "localhost"
os.environ["MASTER_PORT"] = "29501"
os.environ["TORCH_CPP_LOG_LEVEL"]="INFO"
os.environ["TORCH_DISTRIBUTED_DEBUG"] = "DETAIL"
mp.spawn(worker, nprocs=2, args=())
With the NCCL backend, such an application would likely result in a hang which can be challenging to root-cause in nontrivial scenarios. If the user enables
TORCH_DISTRIBUTED_DEBUG=DETAIL and reruns the application, the following error message reveals the root cause:
work = default_pg.allreduce([tensor], opts)
RuntimeError: Error when verifying shape tensors for collective ALLREDUCE on rank 0. This likely indicates that input shapes into the collective are mismatched across ranks. Got shapes: 10
[ torch.LongTensor{1} ]
:::{note}
For fine-grained control of the debug level during runtime the functions {func}torch.distributed.set_debug_level, {func}torch.distributed.set_debug_level_from_env, and
{func}torch.distributed.get_debug_level can also be used.
:::
In addition, TORCH_DISTRIBUTED_DEBUG=DETAIL can be used in conjunction with TORCH_SHOW_CPP_STACKTRACES=1 to log the entire callstack when a collective desynchronization is detected. These
collective desynchronization checks will work for all applications that use c10d collective calls backed by process groups created with the
{func}torch.distributed.init_process_group and {func}torch.distributed.new_group APIs.
torch.distributed.debug HTTP Server
The torch.distributed.debug module provides an HTTP server that can be used
to debug distributed applications. It lets you inspect live distributed
training jobs across all ranks from a single browser tab — collecting stack
traces, flight-recorder events, NCCL traces, profiler captures, wait-counter
metrics, and TCPStore contents without restarting or redeploying your job.
:::{warning} The debug server is intended for trusted network environments only. It is not designed to be secure and must not be exposed to the public internet. :::
:::{note} This is an experimental feature and may change at any time. :::
.. automodule:: torch.distributed.debug
:members:
:undoc-members:
:show-inheritance:
:special-members: __init__
:member-order: bysource
Architecture Overview
The debug server has a two-tier architecture:
┌───────────────────────────────────┐
│ Frontend Server (rank 0) │
│ HTTP server on a fixed port │
│ Renders HTML dashboards │
│ Fans out requests to all ranks │
└──────────┬────────────────────────┘
│ HTTP POST /handler/<endpoint>?<args>
▼
┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐
│ WorkerServer (0) │ │ WorkerServer (1) │ │ WorkerServer (N) │
│ Per-rank C++ │ │ Per-rank C++ │ │ Per-rank C++ │
│ HTTP server │ │ HTTP server │ │ HTTP server │
│ Exposes handlers │ │ Exposes handlers │ │ Exposes handlers │
└──────────────────┘ └──────────────────┘ └──────────────────┘
-
WorkerServer (
_WorkerServer): A lightweight C++ HTTP server started on every rank. It serves handler endpoints registered via_register_handler()(Python) orRegisterHandler(C++). Each handler receives a_Requestand writes to a_Response. -
FrontendServer: A Python HTTP server that starts only on rank 0. It aggregates data from all worker servers and renders HTML dashboards using Jinja2 templates.
-
TCPStore: Workers publish their addresses (hostname + port) to the existing
TCPStoreso the frontend knows where to find each rank.
Quick Start
Prerequisites
Install required dependencies (not bundled with PyTorch by default):
pip install jinja2 aiohttp tabulate
aiohttp is optional — the server falls back to requests + thread pool if
aiohttp is unavailable.
Basic Usage
Call start_debug_server() after dist.init_process_group() on every rank:
import torch
import torch.distributed as dist
from torch.distributed.debug import start_debug_server, stop_debug_server
dist.init_process_group("nccl")
# Start the debug server on all ranks.
# The frontend (browser UI) is served on rank 0 at port 25999.
start_debug_server(port=25999)
# ... your training loop ...
stop_debug_server()
dist.destroy_process_group()
Then open http://<rank0-hostname>:25999 in a browser.
Minimal torchrun Example
# train.py
import torch
import torch.distributed as dist
from torch.distributed.debug import start_debug_server
def main():
dist.init_process_group("nccl")
start_debug_server()
rank = dist.get_rank()
device = torch.device(f"cuda:{rank}")
model = torch.nn.Linear(10, 10).to(device)
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[rank])
for _ in range(1000):
x = torch.randn(32, 10, device=device)
loss = model(x).sum()
loss.backward()
dist.destroy_process_group()
if __name__ == "__main__":
main()
torchrun --nproc-per-node=2 train.py
# Open http://localhost:25999
For an end-to-end NCCL failure example, see
{download}verify_nccl2_flight_recorder.py <../../torch/distributed/examples/verify_nccl2_flight_recorder.py>.
The example deliberately hangs an NCCL collective and verifies that the c10d
health check causes the debug server to write a Flight Recorder dump for every
rank. Run it on a host with at least two GPUs:
torchrun --standalone --nproc-per-node=2 \
torch/distributed/examples/verify_nccl2_flight_recorder.py
Configuration Reference
start_debug_server() accepts the following parameters:
+-------------------+----------------------------+-----------+-----------------------------------------------------------------------+
| Parameter | Type | Default | Description |
+===================+============================+===========+=======================================================================+
| ``port`` | ``int`` | ``25999`` | Port for the frontend HTTP server (rank 0 only). |
+-------------------+----------------------------+-----------+-----------------------------------------------------------------------+
| ``worker_port`` | ``int`` | ``0`` | Port for the per-rank worker server. ``0`` = ephemeral. |
+-------------------+----------------------------+-----------+-----------------------------------------------------------------------+
| ``start_method`` | ``str | None`` | ``None`` | Multiprocessing start method (``"fork"``, ``"spawn"``, |
| | | | ``"forkserver"``). ``"spawn"`` recommended with CUDA. |
+-------------------+----------------------------+-----------+-----------------------------------------------------------------------+
| ``dump_dir`` | ``str | None`` | ``None`` | Directory for periodic debug dumps. ``None`` disables dumping. |
+-------------------+----------------------------+-----------+-----------------------------------------------------------------------+
| ``dump_interval`` | ``float`` | ``60.0`` | Seconds between periodic dumps. |
+-------------------+----------------------------+-----------+-----------------------------------------------------------------------+
| ``enabled_dumps`` | ``set[str] | None`` | ``None`` | Handler dump filenames to enable (e.g. ``{"stacks", "fr_trace"}``). |
| | | | ``None`` = default set. |
+-------------------+----------------------------+-----------+-----------------------------------------------------------------------+
| ``handlers`` | ``list[DebugHandler] | ``None`` | Custom handler list. ``None`` = all default handlers. |
| | | None`` | | |
+-------------------+----------------------------+-----------+-----------------------------------------------------------------------+
| ``fetch_timeout`` | ``float`` | ``60.0`` | Timeout (seconds) when fetching data from workers. |
+-------------------+----------------------------+-----------+-----------------------------------------------------------------------+
Environment Variables
The debug server reads these standard environment variables (set automatically
by torchrun / TorchElastic):
+-------------------+------------------------------------------+
| Variable | Description |
+===================+==========================================+
| ``RANK`` | Current process rank. |
+-------------------+------------------------------------------+
| ``WORLD_SIZE`` | Total number of ranks. |
+-------------------+------------------------------------------+
| ``MASTER_ADDR`` | Address of the TCPStore master. |
+-------------------+------------------------------------------+
| ``MASTER_PORT`` | Port of the TCPStore master. |
+-------------------+------------------------------------------+
Frontend Endpoints (Browser UI)
The frontend server (rank 0) exposes the following endpoints. Each one aggregates data from all worker ranks and renders an HTML page.
Home /
The landing page with navigation links to all other endpoints.
Python Stack Traces /stacks
Calls dump_traceback on every worker to collect Python stack traces using
faulthandler.dump_traceback(). Useful for diagnosing hangs or deadlocks
without attaching a debugger. Displays a <pre> block per rank showing the
Python call stack of every thread.
py-spy Stack Traces /pyspy_dump
Calls pyspy_dump on every worker. Uses
py-spy <https://github.com/benfred/py-spy>_ to dump both Python and
optionally native (C/C++) stack traces. Accepts query parameters
native=1 (include native frames) and subprocesses=1 (include
subprocesses). nonblocking=1 is added automatically.
:::{note}
py-spy must be installed and the process must have SYS_PTRACE
capability.
:::
FlightRecorder CPU /fr_trace
Fetches CPU-side flight recorder data from fr_trace_json on all workers,
parses it into structured tables (Groups, Memberships, Collectives, NCCL
Calls), and renders them as HTML tables.
FlightRecorder CPU JSON /fr_trace_json
Same data as /fr_trace but rendered as raw formatted JSON per rank.
FlightRecorder NCCL /fr_trace_nccl
Fetches NCCL-side flight recorder data from dump_nccl_trace_json (with
onlyactive=true) on all workers and renders structured HTML tables.
FlightRecorder NCCL JSON /fr_trace_nccl_json
Same data as /fr_trace_nccl but rendered as raw formatted JSON per rank.
c10d Health Check /c10d_health_check
Fetches the c10d health state from every rank. When any rank reports an
unhealthy backend, the server requests a Flight Recorder dump for that
backend from every worker.
torch.profiler /profile
Triggers torch.profiler.profile() on every worker for a configurable
duration, then returns the Chrome trace JSON. The frontend page provides a
View button per rank that opens the trace directly in
Perfetto UI <https://ui.perfetto.dev/>_ (no download required). Accepts
query parameter duration (profiling duration in seconds, default 1,
range 1–60).
Wait Counters /wait_counters
Fetches wait_counter_values from all workers and renders the JSON data.
Wait counters track time spent waiting in collective operations, useful for
identifying stragglers and load imbalance.
TCPStore Keys /tcpstore
Connects to the TCPStore and lists all keys with their values (truncated to
100 characters). Useful for inspecting the state of the distributed
key-value store.
Worker-Level Endpoints (Per-Rank HTTP API)
Each WorkerServer instance exposes handler endpoints at:
POST http://<worker-host>:<worker-port>/handler/<handler_name>?<params>
The built-in handlers are:
ping — Simple health check. Returns "pong" (text/plain, 200).
curl -X POST \
http://worker-host:port/handler/ping # @lint-ignore
dump_traceback — Python stack traces of all threads (text/plain). Uses
faulthandler.dump_traceback() to capture every thread's Python stack.
Requires the GIL.
curl -X POST \
http://worker-host:port/handler/dump_traceback # @lint-ignore
pyspy_dump — py-spy stack dump output (text/plain). Runs
py-spy dump --pid <pid> to capture stack traces without stopping the
process. Accepts parameters native, subprocesses, and nonblocking.
curl -X POST \
"http://worker-host:port/handler/pyspy_dump?nonblocking=1&native=1" # @lint-ignore
fr_trace_json — CPU flight-recorder trace (application/json). Returns
the flight-recorder ring buffer contents as JSON, including all recorded
collective operations, their metadata, and timing information.
curl -X POST \
http://worker-host:port/handler/fr_trace_json # @lint-ignore
fr_dump_file — Starts a Flight Recorder dump for one backend. The
backend query parameter selects the backend-specific recorder.
curl -X POST \
"http://worker-host:port/handler/fr_dump_file?backend=nccl2" # @lint-ignore
c10d_health_check — Returns the process-wide c10d health state and the
names of any unhealthy backends (application/json).
curl -X POST \
http://worker-host:port/handler/c10d_health_check # @lint-ignore
dump_nccl_trace_json — NCCL flight-recorder trace (application/json).
Only available when built with NCCL support. Accepts parameters
includecollectives (true/false, default true) and
onlyactive (true/false, default false).
curl -X POST \
"http://worker-host:port/handler/dump_nccl_trace_json?onlyactive=true" # @lint-ignore
dump_nccl_trace_pickle — NCCL trace in pickle format
(application/octet-stream). Useful for programmatic analysis. Accepts
parameters includecollectives (default true),
includestacktraces (default true), and onlyactive (default
false).
curl -X POST \
--output trace.pkl \
"http://worker-host:port/handler/dump_nccl_trace_pickle?onlyactive=true" # @lint-ignore
torch_profile — Chrome trace JSON (application/json). Runs
torch.profiler.profile() for the specified duration and returns the
Chrome trace format JSON. Requires parameter duration (seconds).
curl -X POST \
--output trace.json \
"http://worker-host:port/handler/torch_profile?duration=5" # @lint-ignore
# Open trace.json in chrome://tracing or https://ui.perfetto.dev
wait_counter_values — Wait counter values (application/json). Returns
a JSON object with wait-counter metrics tracking time spent waiting in
distributed collective operations.
curl -X POST \
http://worker-host:port/handler/wait_counter_values # @lint-ignore
Periodic Dumping
Enable periodic dumping to automatically save debug data to disk at regular intervals. This is useful for post-mortem analysis when a job hangs or crashes.
start_debug_server(
dump_dir="/shared/nfs/debug_dumps",
dump_interval=120.0, # dump every 2 minutes
enabled_dumps={"stacks", "fr_trace", "pyspy_dump", "wait_counters", "tcpstore"},
)
Dump files are saved as <handler_name>_<timestamp>.txt (e.g.,
stacks_20250330_192000.txt).
Handlers that support dumping:
+------------------------------------+------------------------+---------------------------------------------------+
| Handler | Dump filename | Content |
+====================================+========================+===================================================+
| ``StacksHandler`` | ``stacks`` | Python stack traces for all ranks. |
+------------------------------------+------------------------+---------------------------------------------------+
| ``PySpyHandler`` | ``pyspy_dump`` | py-spy stack dumps (nonblocking) for all ranks. |
+------------------------------------+------------------------+---------------------------------------------------+
| ``FlightRecorderHandler`` | ``fr_trace`` | CPU + NCCL flight-recorder tables. |
+------------------------------------+------------------------+---------------------------------------------------+
| ``C10dHealthCheckHandler`` | ``c10d_health_check`` | c10d health and backend Flight Recorder dumps. |
+------------------------------------+------------------------+---------------------------------------------------+
| ``WaitCountersHandler`` | ``wait_counters`` | Wait counter JSON for all ranks. |
+------------------------------------+------------------------+---------------------------------------------------+
| ``TCPStoreHandler`` | ``tcpstore`` | All TCPStore key-value pairs. |
+------------------------------------+------------------------+---------------------------------------------------+
By default (when enabled_dumps=None), "stacks", "fr_trace", and
"c10d_health_check" are enabled.
Registering Custom Handlers
You can extend the debug server with custom frontend handlers by subclassing
{class}~torch.distributed.debug._frontend.DebugHandler:
class DebugHandler(ABC):
fetch_timeout: float = _DEFAULT_FETCH_TIMEOUT
@abstractmethod
def routes(self) -> list[Route]: ...
@abstractmethod
def nav_links(self) -> list[NavLink]: ...
def templates(self) -> dict[str, str]:
return {}
def dump(self) -> str | None:
return None
def dump_filename(self) -> str:
return type(self).__name__.lower()
routes()— URL paths and their request handlers.nav_links()— links shown in the navigation bar.templates()— optional Jinja2 templates for HTML rendering.dump()/dump_filename()— optional support for periodic dumping.
For a complete example, see
StacksHandler <https://github.com/pytorch/pytorch/blob/main/torch/distributed/debug/_debug_handlers.py>_
in torch/distributed/debug/_debug_handlers.py.
Pass custom handlers to start_debug_server:
from torch.distributed.debug._debug_handlers import default_handlers
handlers = default_handlers() + [MyCustomHandler()]
start_debug_server(handlers=handlers)
Debug Server Troubleshooting
AssertionError: debug server already started
start_debug_server() was called twice. Ensure you only call it once per
process.
Workers fail to respond (408/503 errors)
- Check that all ranks have started and registered their addresses in TCPStore.
- Increase
fetch_timeoutfor large clusters or slow networks. - Verify network connectivity between rank 0 and all worker hosts.
ImportError: No module named 'jinja2'
Install the required dependencies: pip install jinja2 aiohttp tabulate
py-spy returns errors
- Ensure
py-spyis installed:pip install py-spy - The process may need
SYS_PTRACEcapability. In Docker usedocker run --cap-add SYS_PTRACE ... - On Linux, you may need to set
echo 0 > /proc/sys/kernel/yama/ptrace_scope
Perfetto UI popup blocked
Allow popups for the debug server's origin in your browser settings. The
/profile page opens Perfetto UI in a new window using window.open().
Frontend server not reachable
- Ensure port
25999(or your custom port) is not blocked by a firewall. - The frontend only starts on rank 0. Connect to the rank 0 host.
- Check the logs for
Frontend server started on port <port>.
spawn start method required with CUDA
If you see CUDA re-initialization errors, use
start_debug_server(start_method="spawn") to ensure the frontend server
process does not inherit CUDA state from the parent process.
Logging
In addition to explicit debugging support via {func}torch.distributed.monitored_barrier and TORCH_DISTRIBUTED_DEBUG, the underlying C++ library of torch.distributed also outputs log
messages at various levels. These messages can be helpful to understand the execution state of a distributed training job and to troubleshoot problems such as network connection failures. The
following matrix shows how the log level can be adjusted via the combination of TORCH_CPP_LOG_LEVEL and TORCH_DISTRIBUTED_DEBUG environment variables.
TORCH_CPP_LOG_LEVEL |
TORCH_DISTRIBUTED_DEBUG |
Effective Log Level |
|---|---|---|
ERROR |
ignored | Error |
WARNING |
ignored | Warning |
INFO |
ignored | Info |
INFO |
INFO |
Debug |
INFO |
DETAIL |
Trace (a.k.a. All) |
Distributed components raise custom Exception types derived from RuntimeError:
torch.distributed.DistError: This is the base type of all distributed exceptions.torch.distributed.DistBackendError: This exception is thrown when a backend-specific error occurs. For example, if theNCCLbackend is used and the user attempts to use a GPU that is not available to theNCCLlibrary.torch.distributed.DistNetworkError: This exception is thrown when networking libraries encounter errors (ex: Connection reset by peer)torch.distributed.DistStoreError: This exception is thrown when the Store encounters an error (ex: TCPStore timeout)
.. autoclass:: torch.distributed.DistError
.. autoclass:: torch.distributed.DistBackendError
.. autoclass:: torch.distributed.DistNetworkError
.. autoclass:: torch.distributed.DistStoreError
If you are running single node training, it may be convenient to interactively breakpoint your script. We offer a way to conveniently breakpoint a single rank:
.. autofunction:: torch.distributed.breakpoint
Watchdog (Experimental)
The torch.distributed._watchdog module provides a pure-Python watchdog for
detecting hung operations in Python-based distributed backends and related
distributed primitives. It monitors both CPU-side hangs (e.g., a stuck
rendezvous) and GPU-side hangs (e.g., a kernel that never completes) by running
an asyncio event loop on a background daemon thread. By default, timeouts dump
all thread stack traces and abort the process.
:::{warning} This module is experimental and subject to change. :::
Arguments passed to {func}~torch.distributed._watchdog.init override these environment variables:
:header-rows: 1
* - **Variable**
- **Description**
* - ``TORCH_WATCHDOG_POLL_INTERVAL_SECS``
- Seconds between CUDA event polls. Default: ``1.0``.
* - ``TORCH_WATCHDOG_HEALTH_INTERVAL_SECS``
- Seconds between health pings of the watchdog event loop. Default: ``30.0``.
* - ``TORCH_WATCHDOG_STUCK_ACTION``
- Action when the event loop does not answer a health ping: ``log``, ``abort`` or ``exit``. Default: ``log``.
.. currentmodule:: torch.distributed._watchdog
.. autofunction:: init
.. autofunction:: shutdown
.. autofunction:: stream_timeout
.. autofunction:: cpu_timeout
.. autofunction:: op_timeout
Read More
:caption: torch.distributed submodules
:maxdepth: 1
distributed/custom_backends
torch.distributed.tensor <distributed/tensor>
torch.distributed.functional_collectives <distributed/functional_collectives>
torch.distributed.algorithms.join <distributed/algorithms.join>
torch.distributed.elastic <distributed/elastic>
torch.distributed.fsdp <distributed/fsdp>
torch.distributed.fsdp.fully_shard <distributed/fsdp.fully_shard>
torch.distributed.tensor.parallel <distributed/tensor.parallel>
torch.distributed.optim <distributed/optim>
torch.distributed.pipelining <distributed/pipelining>
torch.distributed._symmetric_memory <distributed/symmetric_memory>
torch.distributed._transport <distributed/transport>
torch.distributed.checkpoint <distributed/checkpoint>
distributed/ddp_comm_hooks
distributed/rpc
% Distributed modules that are missing specific entries.
% Adding them here for tracking purposes until they are more permanently fixed.
.. py:module:: torch.distributed.algorithms
.. py:module:: torch.distributed.algorithms.ddp_comm_hooks
.. py:module:: torch.distributed.algorithms.model_averaging
.. py:module:: torch.distributed.elastic
.. py:module:: torch.distributed.elastic.utils
.. py:module:: torch.distributed.elastic.utils.data
.. py:module:: torch.distributed.launcher
.. py:module:: torch.distributed.nn
.. py:module:: torch.distributed.nn.api
.. py:module:: torch.distributed.nn.jit
.. py:module:: torch.distributed.nn.jit.templates
.. py:module:: torch.distributed.algorithms.ddp_comm_hooks.ddp_zero_hook
.. py:module:: torch.distributed.algorithms.ddp_comm_hooks.debugging_hooks
.. py:module:: torch.distributed.algorithms.ddp_comm_hooks.default_hooks
.. py:module:: torch.distributed.algorithms.ddp_comm_hooks.mixed_precision_hooks
.. py:module:: torch.distributed.algorithms.ddp_comm_hooks.optimizer_overlap_hooks
.. py:module:: torch.distributed.algorithms.ddp_comm_hooks.post_localSGD_hook
.. py:module:: torch.distributed.algorithms.ddp_comm_hooks.powerSGD_hook
.. py:module:: torch.distributed.algorithms.ddp_comm_hooks.quantization_hooks
.. py:module:: torch.distributed.algorithms.join
.. py:module:: torch.distributed.algorithms.model_averaging.averagers
.. py:module:: torch.distributed.algorithms.model_averaging.hierarchical_model_averager
.. py:module:: torch.distributed.algorithms.model_averaging.utils
.. py:module:: torch.distributed.argparse_util
.. py:module:: torch.distributed.c10d_logger
.. py:module:: torch.distributed.checkpoint.api
.. py:module:: torch.distributed.checkpoint.default_planner
.. py:module:: torch.distributed.checkpoint.filesystem
.. py:module:: torch.distributed.checkpoint.hf_storage
.. py:module:: torch.distributed.checkpoint.quantized_hf_storage
.. py:module:: torch.distributed.checkpoint.metadata
.. py:module:: torch.distributed.checkpoint.optimizer
.. py:module:: torch.distributed.checkpoint.planner
.. py:module:: torch.distributed.checkpoint.planner_helpers
.. py:module:: torch.distributed.checkpoint.resharding
.. py:module:: torch.distributed.checkpoint.state_dict_loader
.. py:module:: torch.distributed.checkpoint.state_dict_saver
.. py:module:: torch.distributed.checkpoint.stateful
.. py:module:: torch.distributed.checkpoint.storage
.. py:module:: torch.distributed.checkpoint.utils
.. py:module:: torch.distributed.collective_utils
.. autofunction:: torch.distributed.collective_utils.all_gather_object_enforce_type
.. py:module:: torch.distributed.constants
.. py:module:: torch.distributed.device_mesh
.. py:module:: torch.distributed.distributed_c10d
.. py:module:: torch.distributed.elastic.agent.server.api
.. py:module:: torch.distributed.elastic.agent.server.local_elastic_agent
.. py:module:: torch.distributed.elastic.events.api
.. py:module:: torch.distributed.elastic.events.handlers
.. py:module:: torch.distributed.elastic.metrics.api
.. py:module:: torch.distributed.elastic.multiprocessing.api
.. py:module:: torch.distributed.elastic.multiprocessing.errors.error_handler
.. py:module:: torch.distributed.elastic.multiprocessing.errors.handlers
.. py:module:: torch.distributed.elastic.multiprocessing.redirects
.. py:module:: torch.distributed.elastic.multiprocessing.tail_log
.. py:module:: torch.distributed.elastic.rendezvous.api
.. py:module:: torch.distributed.elastic.rendezvous.c10d_rendezvous_backend
.. py:module:: torch.distributed.elastic.rendezvous.dynamic_rendezvous
.. py:module:: torch.distributed.elastic.rendezvous.etcd_rendezvous
.. py:module:: torch.distributed.elastic.rendezvous.etcd_rendezvous_backend
.. py:module:: torch.distributed.elastic.rendezvous.etcd_server
.. py:module:: torch.distributed.elastic.rendezvous.etcd_store
.. py:module:: torch.distributed.elastic.rendezvous.static_tcp_rendezvous
.. py:module:: torch.distributed.elastic.rendezvous.utils
.. py:module:: torch.distributed.elastic.timer.api
.. py:module:: torch.distributed.elastic.timer.file_based_local_timer
.. py:module:: torch.distributed.elastic.timer.local_timer
.. py:module:: torch.distributed.elastic.utils.api
.. py:module:: torch.distributed.elastic.utils.data.cycling_iterator
.. py:module:: torch.distributed.elastic.utils.data.elastic_distributed_sampler
.. py:module:: torch.distributed.elastic.utils.distributed
.. py:module:: torch.distributed.elastic.utils.log_level
.. py:module:: torch.distributed.elastic.utils.logging
.. py:module:: torch.distributed.elastic.utils.store
.. py:module:: torch.distributed.fsdp.api
.. py:module:: torch.distributed.fsdp.fully_sharded_data_parallel
.. py:module:: torch.distributed.fsdp.sharded_grad_scaler
.. py:module:: torch.distributed.fsdp.wrap
.. py:module:: torch.distributed.launcher.api
.. autofunction:: torch.distributed.launcher.api.launch_agent
.. py:module:: torch.distributed.logging_handlers
.. py:module:: torch.distributed.nn.api.remote_module
.. py:module:: torch.distributed.nn.functional
.. py:module:: torch.distributed.nn.jit.instantiator
.. py:module:: torch.distributed.nn.jit.templates.remote_module_template
.. py:module:: torch.distributed.optim.apply_optimizer_in_backward
.. py:module:: torch.distributed.optim.functional_adadelta
.. py:module:: torch.distributed.optim.functional_adagrad
.. py:module:: torch.distributed.optim.functional_adam
.. py:module:: torch.distributed.optim.functional_adamax
.. py:module:: torch.distributed.optim.functional_adamw
.. py:module:: torch.distributed.optim.functional_rmsprop
.. py:module:: torch.distributed.optim.functional_rprop
.. py:module:: torch.distributed.optim.functional_sgd
.. py:module:: torch.distributed.optim.named_optimizer
.. py:module:: torch.distributed.optim.optimizer
.. py:module:: torch.distributed.optim.post_localSGD_optimizer
.. py:module:: torch.distributed.optim.utils
.. py:module:: torch.distributed.optim.zero_redundancy_optimizer
.. py:module:: torch.distributed.remote_device
.. py:module:: torch.distributed.rendezvous
.. py:module:: torch.distributed.rpc.api
.. py:module:: torch.distributed.rpc.backend_registry
.. py:module:: torch.distributed.rpc.constants
.. py:module:: torch.distributed.rpc.functions
.. py:module:: torch.distributed.rpc.internal
.. py:module:: torch.distributed.rpc.options
.. py:module:: torch.distributed.rpc.rref_proxy
.. py:module:: torch.distributed.rpc.server_process_global_profiler
.. py:module:: torch.distributed.tensor.parallel.api
.. py:module:: torch.distributed.tensor.parallel.ddp
.. py:module:: torch.distributed.tensor.parallel.fsdp
.. py:module:: torch.distributed.tensor.parallel.input_reshard
.. py:module:: torch.distributed.tensor.parallel.loss
.. py:module:: torch.distributed.tensor.parallel.style
.. py:module:: torch.distributed.utils
.. py:module:: torch.distributed.checkpoint.state_dict