DDP communication hook is a generic interface to control how to communicate
gradients across workers by overriding the vanilla allreduce in
DistributedDataParallel.
A few built-in communication hooks are provided,
and users can easily apply any of these hooks to optimize communication.
Besides, the hook interface can also support user-defined communication
strategies for more advanced use cases.
How to Use a Communication Hook?
To use a communication hook, the user just needs to let the DDP model register
the hook before the training loop as below.
A communication hook provides a flexible way to allreduce gradients.
Therefore, it mainly operates on the gradients on each replica before allreduce,
which are bucketized to increase the overlap between communication and computation.
Particularly, represents a bucket of gradient tensors to be allreduced.
This class mainly passes a flattened gradient tensor
(returned by buffer())
to DDP communication hook.
This tensor can be further decomposed into a list of per-parameter tensors within this bucket
(returned by get_per_parameter_tensors())
to apply layer-wise operations.
Whether this bucket is the last bucket to allreduce in an iteration.
This also means that this bucket corresponds to the first few layers in the forward pass.
Registers the hooks of torch.distributed.algorithms.ddp_comm_hooks
to the DDP model. User can specify the type of hook as an enum
DDPCommHookType type using comm_hook_type input. State input will
be passed to the model.
Uses Python comm hook implementations.
This DDP communication hook is used for running post-localSGD algorithm,
by combining with a model averaging component (e.g.,
PeriodicModelAverager)
that runs after the optimizer step.
Parameters:
state (PostLocalSGDState) – State information to run post-localSGD.
Users mainly need to tune start_localSGD_iter to determine when to start local SGD.
bucket (dist.GradBucket) – Bucket that stores a 1D flattened gradient tensor that batches multiple per-variable tensors.
Note that since DDP comm hook only supports single process single device mode,
only exactly one tensor is stored in this bucket.
Modify hook to overlap ZeroRedundancyOptimizer optimizer step with DistributedDataParallel backward pass.
This approach overlaps the optimizer computation and communication with the
backward communication. In particular, the backward computation proceeds
contiguously, and the optimizer computation follows, overlapping with
outstanding backward communication (i.e. all-reduces) and possibly other
optimizer communication (i.e. broadcasts).
The optimizer step computation begins after the last gradient bucket computation has finished.
This approach may be preferred over
if communication is relatively slow compared to computation.
Modify hook to overlap ZeroRedundancyOptimizer optimizer step with DistributedDataParallel backward pass
This approach overlaps the optimizer computation and communication with the
backward computation and communication. In particular, once a bucket’s
gradients have been computed, the optimizer computation using those
gradients is launched (though the actual computation must wait for the
bucket’s all-reduce to complete). This yields an interleaving of all-
reduces and broadcasts in the communication stream.
This approach may be preferred over if
communication is relatively fast compared to computation.
Apply``torch.quantize_per_channel`` logic to DDP using allgather protocol.
Compared to per-tensor, the main motivation of per-channel is
for considerably large tensors such as a tensor that contains 6 million
elements quantizing per a bucket size of 512 (or 128) elements may significantly
increase the resolution.
It first splits GradBucket tensor into multiple chunks (channels) of bucket_size
elements. Then, workers allgather the scales and zero points of their own
GradBucket prior to the quantization. After all workers have that information,
the first callback called quantizes worker’s
own gradient tensor, and uses to communicate these across all workers.
The final callback called , dequantizes, flattens, and
aggregates each quantized gradient tensor locally and returns the mean.
Apply torch.quantize_per_tensor logic to DDP using allgather protocol.
Workers first allgather the scale and zero point of their own
GradBucket prior to the quantization. After all workers have that information,
the first then callback called quantize_and_allgather quantizes worker’s
own gradient tensor, and uses allgather to communicate these across all workers.
The final callback called , dequantizes and
aggregates each quantized gradient tensor locally and returns the mean.
Default Communication Hooks
Default communication hooks are simple stateless hooks, so the input state
in register_comm_hook is either a process group or None.
The input bucket is a torch.distributed.GradBucket object.
Once gradient tensors are aggregated across all workers, its then
callback takes the mean and returns the result.
If user registers this DDP communication hook,
DDP results is expected to be same as the case where no hook was registered.
Hence, this won’t change behavior of DDP and user can use this as a reference
or modify this hook to log useful information or any other purposes while
unaffecting DDP behavior.
Compress by casting GradBucket to torch.float16 divided by process group size.
This DDP communication hook implements a simple gradient compression
approach that casts GradBucket tensor to half-precision floating-point format (torch.float16)
and then divides it by the process group size.
It allreduces those float16 gradient tensors. Once compressed gradient
tensors are allreduced, the chained callback decompress casts it back to the input data type (such as ).
Warning: This API is experimental, and it requires NCCL version later than 2.9.6.
This DDP communication hook implements a simple gradient compression
approach that casts GradBucket tensor to half-precision
Brain floating point format (torch.bfloat16)
and then divides it by the process group size.
It allreduces those bfloat16 gradient tensors. Once compressed gradient
tensors are allreduced, the chained callback decompress casts it back to the input data type (such as float32).
Example::
Additionally, a communication hook wrapper is provided to support fp16_compress_hook() or bf16_compress_hook() as a wrapper,
which can be combined with other communication hooks.
Cast input tensor to torch.float16, cast result of hook back to input dtype.
This wrapper casts the input gradient tensor of a given DDP communication hook to half-precision
floating point format (torch.float16), and casts the resulting tensor of the given hook back to
the input data type, such as float32.
Therefore, fp16_compress_hook is equivalent to fp16_compress_wrapper(allreduce_hook).
Warning: This API is experimental, and it requires NCCL version later than 2.9.6.
This wrapper casts the input gradient tensor of a given DDP communication hook to half-precision
Brain floating point format (torch.bfloat16),
and casts the resulting tensor of the given hook back to the input data type, such as float32.
Therefore, bf16_compress_hook is equivalent to bf16_compress_wrapper(allreduce_hook).
Example::
PowerSGD Communication Hook
PowerSGD (Vogels et al., NeurIPS 2019)
is a gradient compression algorithm, which can provide very high compression
rates and accelerate bandwidth-bound distributed training.
This algorithm needs to maintain both some hyperparameters and the internal
state. Therefore, PowerSGD communication hook is a stateful hook,
and the user needs to provide a state object defined as below.
Store both the algorithm’s hyperparameters and internal state for all gradients during training.
Particularly, matrix_approximation_rank and start_powerSGD_iter are the main hyperparameters that should be tuned by the user.
For performance, we suggest to keep binary hyperparameters use_error_feedback and warm_start on.
matrix_approximation_rank controls the size of compressed low-rank tensors, which determines the compression rate. The lower the rank, the stronger the compression.
1.1. If matrix_approximation_rank is too low, the full model quality will need more training steps to reach or will never reach and yield loss in accuracy.
1.2. The increase of matrix_approximation_rank can substantially increase the computation costs of the compression, and the accuracy may not be further improved beyond a certain threshold.
Return a future that wraps the input, so it is a no-op that does not incur any communication overheads.
This hook should only be used for headroom analysis of allreduce optimization,
instead of the normal gradient synchronization.
For example, if only less than 10% speedup of training time can be observed after this hook is registered,
it usually implies that allreduce is not a performance bottleneck for this case.
Such instrumentation can be particularly useful
if GPU traces cannot be easily retrieved or the trace analysis is complicated by
some factors such as the overlap between allreduce and computation or the desynchronization across ranks.
A stateful communication hook can be saved as a part of model checkpointing to enable trainer restarts.
To make a hook serializable, __setstate__ and __getstate__ should be defined.
PowerSGDState has __setstate__ and __getstate__ implemented and can be used as a reference.
Many thanks to PowerSGD paper author Thijs Vogels for the code review on
PowerSGD communication hook, as well as the
comparison experiments,
which show that the performance of PowerSGD communication hook is on par with
the implementation in the original paper.
Returns:
Future handler of the communication, which updates the gradients in place.
>>> state=PostLocalSGDState(process_group=process_group,subgroup=subgroup, start_localSGD_iter=10)>>> ddp_model.register_comm_hook(state,post_localSGD_hook)>>> # Also need to establish a model averaging module and run model averaging after ``optimizer.step()``.>>> # Please refer to the examples in ``torch.distributed.algorithms.model_averaging.averagers`` module.
hook_with_zero_step_interleaved()
Parameters:
hook (Callable[[Any, dist.GradBucket], torch.futures.Future]) – the hook
to modify.
shard_buckets (bool) – if True, then the assignment of each
DistributedDataParallel bucket is partitioned across
possibly multiple ZeroRedundancyOptimizer instances (i.e.
across possibly multiple ranks) to approximate uniformity; if
False, then each bucket is wholly assigned to a single
ZeroRedundancyOptimizer instance (i.e. to a single rank).
Returns:
The modified hook.
Raises:
ValueError – if zero was constructed with overlap_with_ddp=False.
RuntimeError – if using any backend other than NCCL/HCCL since currently
Gloo may hang.
shard_buckets (bool) – if True, then the assignment of each
DistributedDataParallel bucket is partitioned across
possibly multiple ZeroRedundancyOptimizer instances (i.e.
across possibly multiple ranks) to approximate uniformity; if
False, then each bucket is wholly assigned to a single
ZeroRedundancyOptimizer instance (i.e. to a single rank).
Returns:
The modified hook.
Raises:
ValueError – if zero was constructed with overlap_with_ddp=False.
RuntimeError – if using any backend other than NCCL since currently
Gloo may hang.
To tune matrix_approximation_rank, we suggest to start from 1 and increase by factors of 2 (like an exponential grid search, 1, 2, 4, …), until a satisfactory accuracy is reached. Typically only a small value 1-4 is used. For some NLP tasks (as shown in Appendix D of the original paper), this value has been increased to 32.
start_powerSGD_iter defers PowerSGD compression until step start_powerSGD_iter, and vanilla allreduce runs prior to step start_powerSGD_iter. This hybrid scheme of vanilla allreduce + PowerSGD can effectively improve the accuracy, even a relatively small matrix_approximation_rank is used. This is because that, the beginning of training phase is usually very sensitive to inaccurate gradients, and compressing gradients too early may make the training quickly take a suboptimal trajectory, which can result in an irrecoverable impact on the accuracy.
To tune start_powerSGD_iter, we suggest to start with 10% of total training steps, and increase it until a satisfactory accuracy is reached. If there is a warm-up stage in the training, start_powerSGD_iter typically should be no less than the number of warm-up steps.
min_compression_rate is the minimum compression rate required when a layer is compressed. Due to the computation overheads incurred by the compression, a tensor is worth compressing only if there can be sufficient saving in bandwidth, where (num_rows+num_cols)*matrix_approximation_rank*min_compression_rate<num_rows*num_cols. If the specified compression rate threshold cannot be satisfied, the tensor will be directly allreduced without compression.
Compression statistics are logged every compression_stats_logging_frequency iterations once PowerSGD compression starts.
orthogonalization_epsilon can be a very small value (e.g., 1e-8) added to every normalized matrix column in orthogonalization step, to prevent div-by-zero error if any column has all 0s. If this can already be prevented (e.g., by batch normalization), an epsilon of 0 is recommended for accuracy.
batch_tensors_with_same_shape controls whether to compress and decompress tensors with same shape in a batched operation to achieve higher parallelism. Note that you should also increase the bucket size (i.e., bucket_cap_mb arg in DDP constructor) to make more same-shaped tensors appear in the same bucket, however this may reduce the overlap between computation and communication, and increase the memory footprint due to stacking the tensors of the same shape. Set to True if the compression / decompression computation is a bottleneck.
Implement PowerSGD algorithm.
This DDP communication hook implements PowerSGD gradient compression
algorithm described in the paper.
Once gradient tensors are aggregated across all workers, this hook applies
compression as follows:
Views the input flattened 1D gradient tensor as a list of per-parameter tensors, and divides all the tensors into two groups:
1.1 The tensors that should be compressed before allreduce, because the compression can give enough saving in bandwidth.
1.2 Rest of the tensors will be directly allreduced without compression, including all the vector tensors (for biases).
Handles uncompressed tensors:
2.1. Allocate contiguous memory for those uncompressed tensors, and allreduces all the uncompressed tensors as a batch, without compression;
2.2. Copies the individual uncompressed tensors from the contiguous memory back to the input tensor.
Handles the tensors that should be compressed by PowerSGD compression:
3.1. For each tensor M, creates two low-rank tensors P and Q for decomposing M,
such that M = PQ^T, where Q is initialized from a standard normal distribution and orthogonalized;
3.2. Computes each P in Ps, which is equal to MQ;
3.3. Allreduces Ps as a batch;
3.4. Orthogonalizes each P in Ps;
3.5. Computes each Q in Qs, which is approximately equal to M^TP;
3.6. Allreduces Qs as a batch;
3.7. Computes each M among all the compressed tensors, which is approximately equal to PQ^T.
Note that this communication hook enforces vanilla allreduce for the first state.start_powerSGD_iter iterations.
This not only gives the user more control over the tradeoff between speedup and accuracy,
but also helps abstract away some complexity of the internal optimization of DDP for future communication hook developers.
Parameters:
state (PowerSGDState) – State information to configure the compression rate and support error feedback, warm start, etc.
To tune the compression configs, mainly need to tune matrix_approximation_rank, start_powerSGD_iter
and min_compression_rate.
bucket (dist.GradBucket) – Bucket that stores a 1D flattened gradient tensor that batches multiple per-variable tensors.
Note that since DDP comm hook only supports single process single device mode,
only exactly one tensor is stored in this bucket.
Returns:
Future handler of the communication, which updates the gradients in place.
This DDP communication hook implements a simplified PowerSGD gradient compression
algorithm described in the paper.
This variant does not compress the gradients layer by layer,
but instead compresses the flattened input tensor that batches all the gradients.
Therefore, it is faster than powerSGD_hook(),
but usually results in a much lower accuracy, unless matrix_approximation_rank is 1.
Once gradient tensors are aggregated across all workers, this hook applies
compression as follows:
Views the input flattened 1D gradient tensor as a square-shaped tensor M with 0 paddings;
Creates two low-rank tensors P and Q for decomposing M, such that M = PQ^T, where Q is initialized from a standard normal distribution and orthogonalized;
Computes P, which is equal to MQ;
Allreduces P;
Orthogonalizes P;
Computes Q, which is approximately equal to M^TP;
Allreduces Q;
Computes M, which is approximately equal to PQ^T.
Truncates the input tensor to the original length.
Note that this communication hook enforces vanilla allreduce for the first state.start_powerSGD_iter iterations.
This not only gives the user more control over the tradeoff between speedup and accuracy,
but also helps abstract away some complexity of the internal optimization of DDP for future communication hook developers.
Parameters:
state (PowerSGDState) – State information to configure the compression rate and support error feedback, warm start, etc.
To tune the compression configs, mainly need to tune matrix_approximation_rank and start_powerSGD_iter.
bucket (dist.GradBucket) – Bucket that stores a 1D flattened gradient tensor that batches multiple per-variable tensors.
Note that since DDP comm hook only supports single process single device mode,
only exactly one tensor is stored in this bucket.
Returns:
Future handler of the communication, which updates the gradients in place.