DistributedDataParallel
- class torch.nn.parallel.DistributedDataParallel(module, device_ids=None, output_device=None, dim=0, broadcast_buffers=None, , , , , , , , , , , , , , ,
Implement distributed data parallelism based on torch.distributed at module level.
This container provides data parallelism by synchronizing gradients
across each model replica. The devices to synchronize across are
specified by the input process_group, which is the entire world
by default. Note that DistributedDataParallel does not chunk or
otherwise shard the input across participating GPUs; the user is
responsible for defining how to do so, for example through the use
of a DistributedSampler.
See also: Basics and Use nn.parallel.DistributedDataParallel instead of multiprocessing or nn.DataParallel.
The same constraints on input as in torch.nn.DataParallel apply.
Creation of this class requires that torch.distributed to be already
initialized, by calling torch.distributed.init_process_group().
DistributedDataParallel is proven to be significantly faster than
torch.nn.DataParallel for single-node multi-GPU data
parallel training.
To use DistributedDataParallel on a host with N GPUs, you should spawn
up N processes, ensuring that each process exclusively works on a single
GPU from 0 to N-1. This can be done by either setting
CUDA_VISIBLE_DEVICES for every process or by calling the following API for GPUs,
>>> torch.cuda.set_device(i)
or calling the unified API for accelerator,
>>> torch.accelerator.set_device_index(i)
where i is from 0 to N-1. In each process, you should refer the following to construct this module:
>>> if torch.accelerator.is_available():
>>> device_type = torch.accelerator.current_accelerator().type
>>> vendor_backend = torch.distributed.get_default_backend_for_device(device_type)
>>>
>>> torch.distributed
Or you can use the latest API for initialization:
>>> torch.distributed.init_process_group(device_id=i)
In order to spawn up multiple processes per node, you can use either
torch.distributed.launch or torch.multiprocessing.spawn.
module (Module) – module to be parallelized
device_ids (list of int or torch.device) –
CUDA devices.
1) For single-device modules, device_ids can
contain exactly one device id, which represents the only
CUDA device where the input module corresponding to this process resides.
Alternatively, device_ids can also be None.
2) For multi-device modules and CPU modules,
must be .
Example:
>>> torch.distributed.init_process_group(backend='nccl', world_size=4, init_method='...')
>>> net = torch.nn.parallel.DistributedDataParallel(model)
Context manager for training with uneven inputs across processes in DDP.
This context manager will keep track of already-joined DDP processes,
and “shadow” the forward and backward passes by inserting collective
communication operations to match with the ones created by non-joined
DDP processes. This will ensure each collective call has a corresponding
call by already-joined DDP processes, preventing hangs or errors that
would otherwise happen when training with uneven inputs across
processes. Alternatively, if the flag throw_on_early_termination is
specified to be True, all trainers will throw an error once one rank
runs out of inputs, allowing these errors to be caught and handled
according to application logic.
Once all DDP processes have joined, the context manager will broadcast the model corresponding to the last joined process to all processes to ensure the model is the same across all processes (which is guaranteed by DDP).
DDP join hook enables training on uneven inputs by mirroring communications in forward and backward passes.
kwargs (dict) – a dict containing any keyword arguments
to modify the behavior of the join hook at run time; all
Joinable instances sharing the same join context
manager are forwarded the same value for kwargs.
Context manager to disable gradient synchronizations across DDP processes.
Within this context, gradients will be accumulated on module variables, which will later be synchronized in the first forward-backward pass exiting the context.
Example:
>>> ddp = torch.nn.parallel.DistributedDataParallel(model, pg)
>>> with ddp.no_sync():
Register communication hook for user-defined DDP aggregation of gradients across multiple workers.
This hook would be very useful for researchers to try out new ideas. For example, this hook can be used to implement several algorithms like GossipGrad and gradient compression which involve different communication strategies for parameter syncs while running Distributed DataParallel training.
state (object) –
Passed to the hook to maintain any state information during the training process. Examples include error feedback in gradient compression, peers to communicate with next in GossipGrad, etc.
It is locally stored by each worker and shared by all the gradient tensors on the worker.
hook (Callable) –
Callable with the following signature: :
NoneWhen device_ids is None for both cases,
both the input data for the forward pass and the actual module
must be placed on the correct device.
(default: None)
output_device (int or torch.device) – Device location of output for
single-device CUDA modules. For multi-device modules and
CPU modules, it must be None, and the module itself
dictates the output location. (default: device_ids[0]
for single-device modules)
broadcast_buffers (bool or None) –
Flag that enables syncing (broadcasting)
buffers of the module at beginning of the forward
function. (default: None)
init_sync (bool) – Whether to sync during initialization to verify param
shapes and broadcast parameters and buffers.
Note: the deprecated broadcast_buffers=False
excludes buffers from this init sync. The replacement
forward_sync_buffers does not affect init sync.
WARNING: if this is set to False the user is required
to ensure themselves that the weights are the same on
all ranks.
(default: True)
process_group – The process group to be used for distributed data
all-reduction. If None, the default process group, which
is created by torch.distributed.init_process_group(),
will be used. (default: None)
bucket_cap_mb – DistributedDataParallel will bucket parameters into
multiple buckets so that gradient reduction of each
bucket can potentially overlap with backward computation.
bucket_cap_mb controls the bucket size in
MebiBytes (MiB). If None, a default size of 25 MiB
will be used. (default: None)
find_unused_parameters (bool) – Traverse the autograd graph from all
tensors contained in the return value of the
wrapped module’s forward function. Parameters
that don’t receive gradients as part of this
graph are preemptively marked as being ready to
be reduced. In addition, parameters that may have
been used in the wrapped module’s forward
function but were not part of loss computation and
thus would also not receive gradients are
preemptively marked as ready to be reduced.
(default: False)
check_reduction – This argument is deprecated.
gradient_as_bucket_view (bool) – When set to True, gradients will be views
pointing to different offsets of allreduce communication
buckets. This can reduce peak memory usage, where the
saved memory size will be equal to the total gradients
size. Moreover, it avoids the overhead of copying between
gradients and allreduce communication buckets. When
gradients are views, detach_() cannot be called on the
gradients. If hitting such errors, please fix it by
referring to the zero_grad()
function in torch/optim/optimizer.py as a solution.
Note that gradients will be views after first iteration, so
the peak memory saving should be checked after first iteration.
static_graph (bool) –
When set to True, DDP knows the trained graph is
static. Static graph means 1) The set of used and unused
parameters will not change during the whole training loop; in
this case, it does not matter whether users set
find_unused_parameters = True or not. 2) How the graph is trained
will not change during the whole training loop (meaning there is
no control flow depending on iterations).
When static_graph is set to be True, DDP will support cases that
can not be supported in the past:
1) Reentrant backwards.
2) Activation checkpointing multiple times.
3) Activation checkpointing when model has unused parameters.
4) There are model parameters that are outside of forward function.
5) Potentially improve performance when there are unused parameters,
as DDP will not search graph in each iteration to detect unused
parameters when static_graph is set to be True.
To check whether you can set static_graph to be True, one way is to
check ddp logging data at the end of your previous model training,
if ddp_logging_data.get("can_set_static_graph") == True, mostly you
can set static_graph = True as well.
>>> model_DDP = torch.nn.parallel.DistributedDataParallel(model)
>>> # Training loop
>>> ...
>>> ddp_logging_data = model_DDP._get_ddp_logging_data()
>>> static_graph =
delay_all_reduce_named_params (list of tuple of str and torch.nn.Parameter) – a list
of named parameters whose all reduce will be delayed when the gradient of
the parameter specified in param_to_hook_all_reduce is ready. Other
arguments of DDP do not apply to named params specified in this argument
as these named params will be ignored by DDP reducer.
param_to_hook_all_reduce (torch.nn.Parameter) – a parameter to hook delayed all reduce
of parameters specified in delay_all_reduce_named_params.
skip_all_reduce_unused_params – When set to True, DDP will skip reducing unused parameters. This requires that unused parameters remain the same across all ranks throughout the entire training process. If this condition is not met, it may cause desynchronization and result in training hang.
batched_grad_copy (bool) – When set to True, individual per-parameter
gradient-to-bucket copy and division operations are deferred
and flushed as a single _foreach_copy_ plus one flat
div_ when a bucket becomes ready. This reduces per-parameter
kernel launches down to 2 kernels per bucket, which can improve
throughput for models with many small parameters. The
optimization is most effective with
optimizer.zero_grad(set_to_none=True) (the default), where
gradient_as_bucket_view alone cannot avoid copies because
the bucket view alias is destroyed every iteration.
(default: False)
forward_sync_buffers (bool or None) – Flag that enables syncing
(broadcasting) buffers of the module at runtime, including
at the beginning of forward and after uneven-input
joins. Does not affect initialization sync (see
init_sync); buffers are always synced at init
regardless of this flag. Replaces the deprecated
broadcast_buffers argument. When None, defaults
to True. (default: None)
module (Module) – the module to be parallelized.
To use this to enable training with uneven inputs across processes, simply wrap this context manager around your training loop. No further modifications to the model or data loading is required.
divide_by_initial_world_size (bool) – If True, will divide
gradients by the initial world_size DDP training was launched
with. If False, will compute the effective world size
(number of ranks that have not depleted their inputs yet) and
divide gradients by that during allreduce. Set
divide_by_initial_world_size=True to ensure every input
sample including the uneven inputs have equal weight in terms of
how much they contribute to the global gradient. This is
achieved by always dividing the gradient by the initial
world_size even when we encounter uneven inputs. If you set
this to False, we divide the gradient by the remaining
number of nodes. This ensures parity with training on a smaller
world_size although it also means the uneven inputs would
contribute more towards the global gradient. Typically, you
would want to set this to True for cases where the last few
inputs of your training job are uneven. In extreme cases, where
there is a large discrepancy in the number of inputs, setting
this to False might provide better results.
enable (bool) – Whether to enable uneven input detection or not. Pass
in enable=False to disable in cases where you know that
inputs are even across participating processes. Default is
True.
throw_on_early_termination (bool) – Whether to throw an error
or continue training when at least one rank has exhausted
inputs. If True, will throw upon the first rank reaching end
of data. If False, will continue training with a smaller
effective world size until all ranks are joined. Note that if
this flag is specified, then the flag
divide_by_initial_world_size would be ignored. Default
is False.
Example:
>>> import torch
>>> import torch.distributed as dist
>>> import os
>>> import torch.multiprocessing as mp
>>> import torch.nn as nn
>>> # On each spawned worker
>>> def worker(rank):
>>> dist.init_process_group("nccl", rank=rank, world_size=2)
>>> torch.cuda.set_device(rank)
>>> model = nn.Linear(1, 1, bias=False).to(rank)
>>> model = torch.nn.parallel.DistributedDataParallel(
>>> model, device_ids=[rank], output_device=rank
>>> )
>>> # Rank 1 gets one more input than rank 0.
>>> inputs = [torch.tensor([1]).float() for _ in range(10 + rank)]
>>> with model.join():
>>> for _ in range(5):
>>> for inp in inputs:
>>> loss = model(inp).sum()
>>> loss.backward()
>>> # Without the join() API, the below synchronization will hang
>>> # blocking for rank 1's allreduce to complete.
>>> torch.cuda.synchronize(device=rank)
If True, then gradients are divided by the initial world
size that DDP was launched with.
If False, then gradients are divided by the effective world
size (i.e. the number of non-joined processes), meaning that
the uneven inputs contribute more toward the global gradient.
Typically, this should be set to True if the degree of
unevenness is small but can be set to False in extreme
cases for possibly better results.
Default is True.
hook(state: object, bucket: dist.GradBucket) -> torch.futures.Future[torch.Tensor]This function is called once the bucket is ready. The hook can perform whatever processing is needed and return a Future indicating completion of any async work (ex: allreduce). If the hook doesn’t perform any communication, it still must return a completed Future. The Future should hold the new value of grad bucket’s tensors. Once a bucket is ready, c10d reducer would call this hook and use the tensors returned by the Future and copy grads to individual parameters. Note that the future’s return type must be a single tensor.
We also provide an API called get_future to retrieve a
Future associated with the completion of c10d.ProcessGroup.Work.
get_future is currently supported for NCCL and also supported for most
operations on GLOO and MPI, except for peer to peer operations (send/recv).
Below is an example of a noop hook that returns the same tensor.
>>> def noop(state: object, bucket: dist.GradBucket) -> torch.futures.Future[torch.Tensor]:
>>> fut = torch.futures.Future()
>>> fut.set_result(bucket.buffer())
>>> return fut
>>> ddp.register_comm_hook(state=None, hook=noop)
Below is an example of a Parallel SGD algorithm where gradients are encoded before allreduce, and then decoded after allreduce.
>>> def encode_and_decode(state: object, bucket: dist.GradBucket) -> torch.futures.Future[torch.Tensor]:
>>> encoded_tensor =