| 1 |
<!-- |
| 2 |
Copyright 2022 The HuggingFace Team. All rights reserved. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with |
| 5 |
the License. You may obtain a copy of the License at |
| 6 |
|
| 7 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
|
| 9 |
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on |
| 10 |
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the |
| 11 |
specific language governing permissions and limitations under the License. |
| 12 |
|
| 13 |
⚠️ Note that this file is in Markdown but contains specific syntax for our doc-builder (similar to MDX) that may not be |
| 14 |
rendered properly in your Markdown viewer. |
| 15 |
--> |
| 16 |
|
| 17 |
# DDP Communication Hooks |
| 18 |
|
| 19 |
Distributed Data Parallel (DDP) communication hooks provide a generic interface to control how gradients are communicated 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. |
| 20 |
|
| 21 |
|
| 22 |
- **FP16 Compression Hook**: Compresses gradients by casting them to half-precision floating-point format (`torch.float16`), reducing communication overhead. |
| 23 |
- **BF16 Compression Hook**: Similar to FP16, but uses the Brain Floating Point format (`torch.bfloat16`), which can be more efficient on certain hardware. |
| 24 |
- **PowerSGD Hook**: An advanced gradient compression algorithm that provides high compression rates and can accelerate bandwidth-bound distributed training. |
| 25 |
|
| 26 |
In this tutorial, you will see how to quickly set up DDP communication hooks and perform training with the utilities provided in Accelerate, which can be as simple as adding just one new line of code! This demonstrates how to use DDP communication hooks to optimize gradient communication in distributed training with the Accelerate library. |
| 27 |
|
| 28 |
## FP16 Compression Hook |
| 29 |
|
| 30 |
<hfoptions id="fp16"> |
| 31 |
<hfoption id="PyTorch"> |
| 32 |
|
| 33 |
```python |
| 34 |
import torch |
| 35 |
from torch.nn.parallel import DistributedDataParallel as DDP |
| 36 |
from torch.distributed.algorithms.ddp_comm_hooks import default_hooks |
| 37 |
from accelerate.test_utils.testing import get_backend |
| 38 |
|
| 39 |
device_type, _, _ = get_backend() |
| 40 |
device_id = getattr(torch, device_type, torch.cuda).current_device() |
| 41 |
|
| 42 |
class MyModel(torch.nn.Module): |
| 43 |
def __init__(self): |
| 44 |
super().__init__() |
| 45 |
self.layer = torch.nn.Linear(10, 10) |
| 46 |
|
| 47 |
def forward(self, x): |
| 48 |
return self.layer(x) |
| 49 |
|
| 50 |
model = MyModel() |
| 51 |
model = DDP(model, device_ids=[device_id]) |
| 52 |
model.register_comm_hook(state=None, hook=default_hooks.fp16_compress_hook) |
| 53 |
|
| 54 |
# Training loop |
| 55 |
for data, targets in data_loader: |
| 56 |
outputs = model(data) |
| 57 |
loss = criterion(outputs, targets) |
| 58 |
loss.backward() |
| 59 |
optimizer.step() |
| 60 |
optimizer.zero_grad() |
| 61 |
``` |
| 62 |
|
| 63 |
</hfoption> |
| 64 |
<hfoption id="Accelerate"> |
| 65 |
|
| 66 |
```python |
| 67 |
from accelerate import Accelerator, DDPCommunicationHookType, DistributedDataParallelKwargs |
| 68 |
import torch |
| 69 |
|
| 70 |
class MyModel(torch.nn.Module): |
| 71 |
def __init__(self): |
| 72 |
super().__init__() |
| 73 |
self.layer = torch.nn.Linear(10, 10) |
| 74 |
|
| 75 |
def forward(self, x): |
| 76 |
return self.layer(x) |
| 77 |
|
| 78 |
# DDP Communication Hook setup |
| 79 |
ddp_kwargs = DistributedDataParallelKwargs(comm_hook=DDPCommunicationHookType.FP16) |
| 80 |
accelerator = Accelerator(kwargs_handlers=[ddp_kwargs]) |
| 81 |
|
| 82 |
model = MyModel() |
| 83 |
optimizer = torch.optim.Adam(model.parameters()) |
| 84 |
data_loader = DataLoader(dataset, batch_size=16) |
| 85 |
|
| 86 |
model, optimizer, data_loader = accelerator.prepare(model, optimizer, data_loader) |
| 87 |
|
| 88 |
# Training loop |
| 89 |
for data, targets in data_loader: |
| 90 |
outputs = model(data) |
| 91 |
loss = criterion(outputs, targets) |
| 92 |
accelerator.backward(loss) |
| 93 |
optimizer.step() |
| 94 |
optimizer.zero_grad() |
| 95 |
``` |
| 96 |
|
| 97 |
</hfoption> |
| 98 |
</hfoptions> |
| 99 |
|
| 100 |
### BF16 Compression Hook |
| 101 |
|
| 102 |
<Tip warning={true}> |
| 103 |
|
| 104 |
BF16 Compression Hook API is experimental, and it requires NCCL version later than 2.9.6. |
| 105 |
|
| 106 |
</Tip> |
| 107 |
|
| 108 |
<hfoptions id="bf16"> |
| 109 |
<hfoption id="PyTorch"> |
| 110 |
|
| 111 |
```python |
| 112 |
import torch |
| 113 |
from torch.nn.parallel import DistributedDataParallel as DDP |
| 114 |
from torch.distributed.algorithms.ddp_comm_hooks import default_hooks |
| 115 |
from accelerate.test_utils.testing import get_backend |
| 116 |
|
| 117 |
device_type, _, _ = get_backend() |
| 118 |
device_id = getattr(torch, device_type, torch.cuda).current_device() |
| 119 |
|
| 120 |
class MyModel(torch.nn.Module): |
| 121 |
def __init__(self): |
| 122 |
super().__init__() |
| 123 |
self.layer = torch.nn.Linear(10, 10) |
| 124 |
|
| 125 |
def forward(self, x): |
| 126 |
return self.layer(x) |
| 127 |
|
| 128 |
model = MyModel() |
| 129 |
model = DDP(model, device_ids=[device_id]) |
| 130 |
model.register_comm_hook(state=None, hook=default_hooks.bf16_compress_hook) |
| 131 |
|
| 132 |
# Training loop |
| 133 |
for data, targets in data_loader: |
| 134 |
outputs = model(data) |
| 135 |
loss = criterion(outputs, targets) |
| 136 |
loss.backward() |
| 137 |
optimizer.step() |
| 138 |
optimizer.zero_grad() |
| 139 |
``` |
| 140 |
|
| 141 |
</hfoption> |
| 142 |
<hfoption id="Accelerate"> |
| 143 |
|
| 144 |
```python |
| 145 |
from accelerate import Accelerator, DDPCommunicationHookType, DistributedDataParallelKwargs |
| 146 |
import torch |
| 147 |
|
| 148 |
class MyModel(torch.nn.Module): |
| 149 |
def __init__(self): |
| 150 |
super().__init__() |
| 151 |
self.layer = torch.nn.Linear(10, 10) |
| 152 |
|
| 153 |
def forward(self, x): |
| 154 |
return self.layer(x) |
| 155 |
|
| 156 |
# DDP Communication Hook setup |
| 157 |
ddp_kwargs = DistributedDataParallelKwargs(comm_hook=DDPCommunicationHookType.BF16) |
| 158 |
accelerator = Accelerator(kwargs_handlers=[ddp_kwargs]) |
| 159 |
|
| 160 |
model = MyModel() |
| 161 |
optimizer = torch.optim.Adam(model.parameters()) |
| 162 |
data_loader = DataLoader(dataset, batch_size=16) |
| 163 |
|
| 164 |
model, optimizer, data_loader = accelerator.prepare(model, optimizer, data_loader) |
| 165 |
|
| 166 |
# Training loop |
| 167 |
for data, targets in data_loader: |
| 168 |
outputs = model(data) |
| 169 |
loss = criterion(outputs, targets) |
| 170 |
accelerator.backward(loss) |
| 171 |
optimizer.step() |
| 172 |
optimizer.zero_grad() |
| 173 |
``` |
| 174 |
|
| 175 |
</hfoption> |
| 176 |
</hfoptions> |
| 177 |
|
| 178 |
### PowerSGD Hook |
| 179 |
|
| 180 |
<Tip warning={true}> |
| 181 |
|
| 182 |
PowerSGD typically requires extra memory of the same size as the model’s gradients to enable error feedback, which can compensate for biased compressed communication and improve accuracy. |
| 183 |
|
| 184 |
</Tip> |
| 185 |
|
| 186 |
<hfoptions id="powerSGD"> |
| 187 |
<hfoption id="PyTorch"> |
| 188 |
|
| 189 |
```python |
| 190 |
import torch |
| 191 |
from torch.nn.parallel import DistributedDataParallel as DDP |
| 192 |
from torch.distributed.algorithms.ddp_comm_hooks import powerSGD_hook |
| 193 |
from accelerate.test_utils.testing import get_backend |
| 194 |
|
| 195 |
device_type, _, _ = get_backend() |
| 196 |
device_id = getattr(torch, device_type, torch.cuda).current_device() |
| 197 |
|
| 198 |
class MyModel(torch.nn.Module): |
| 199 |
def __init__(self): |
| 200 |
super().__init__() |
| 201 |
self.layer = torch.nn.Linear(10, 10) |
| 202 |
|
| 203 |
def forward(self, x): |
| 204 |
return self.layer(x) |
| 205 |
|
| 206 |
model = MyModel() |
| 207 |
model = DDP(model, device_ids=[device_id]) |
| 208 |
state = powerSGD_hook.PowerSGDState(process_group=None) |
| 209 |
model.register_comm_hook(state=state, hook=powerSGD_hook.powerSGD_hook) |
| 210 |
|
| 211 |
# Training loop |
| 212 |
for data, targets in data_loader: |
| 213 |
outputs = model(data) |
| 214 |
loss = criterion(outputs, targets) |
| 215 |
loss.backward() |
| 216 |
optimizer.step() |
| 217 |
optimizer.zero_grad() |
| 218 |
``` |
| 219 |
|
| 220 |
</hfoption> |
| 221 |
<hfoption id="Accelerate"> |
| 222 |
|
| 223 |
```python |
| 224 |
from accelerate import Accelerator, DDPCommunicationHookType, DistributedDataParallelKwargs |
| 225 |
import torch |
| 226 |
|
| 227 |
class MyModel(torch.nn.Module): |
| 228 |
def __init__(self): |
| 229 |
super().__init__() |
| 230 |
self.layer = torch.nn.Linear(10, 10) |
| 231 |
|
| 232 |
def forward(self, x): |
| 233 |
return self.layer(x) |
| 234 |
|
| 235 |
# DDP Communication Hook setup |
| 236 |
ddp_kwargs = DistributedDataParallelKwargs(comm_hook=DDPCommunicationHookType.POWER_SGD) |
| 237 |
accelerator = Accelerator(kwargs_handlers=[ddp_kwargs]) |
| 238 |
|
| 239 |
model = MyModel() |
| 240 |
optimizer = torch.optim.Adam(model.parameters()) |
| 241 |
data_loader = DataLoader(dataset, batch_size=16) |
| 242 |
|
| 243 |
model, optimizer, data_loader = accelerator.prepare(model, optimizer, data_loader) |
| 244 |
|
| 245 |
# Training loop |
| 246 |
for data, targets in data_loader: |
| 247 |
outputs = model(data) |
| 248 |
loss = criterion(outputs, targets) |
| 249 |
accelerator.backward(loss) |
| 250 |
optimizer.step() |
| 251 |
optimizer.zero_grad() |
| 252 |
``` |
| 253 |
|
| 254 |
</hfoption> |
| 255 |
</hfoptions> |
| 256 |
|
| 257 |
## DDP Communication Hooks utilities |
| 258 |
|
| 259 |
There are two additional utilities for supporting optional functionalities with the communication hooks. |
| 260 |
|
| 261 |
### comm_wrapper |
| 262 |
|
| 263 |
`comm_wrapper` is an option to wrap a communication hook with additional functionality. For example, it can be used to combine FP16 compression with other communication strategies. Currently supported wrappers are `no`, `fp16`, and `bf16`. |
| 264 |
|
| 265 |
```python |
| 266 |
from accelerate import Accelerator, DDPCommunicationHookType, DistributedDataParallelKwargs |
| 267 |
import torch |
| 268 |
|
| 269 |
class MyModel(torch.nn.Module): |
| 270 |
def __init__(self): |
| 271 |
super().__init__() |
| 272 |
self.layer = torch.nn.Linear(10, 10) |
| 273 |
|
| 274 |
def forward(self, x): |
| 275 |
return self.layer(x) |
| 276 |
|
| 277 |
# DDP Communication Hook setup |
| 278 |
ddp_kwargs = DistributedDataParallelKwargs( |
| 279 |
comm_hook=DDPCommunicationHookType.POWER_SGD, |
| 280 |
comm_wrapper=DDPCommunicationHookType.FP16 |
| 281 |
) |
| 282 |
accelerator = Accelerator(kwargs_handlers=[ddp_kwargs]) |
| 283 |
|
| 284 |
model = MyModel() |
| 285 |
optimizer = torch.optim.Adam(model.parameters()) |
| 286 |
data_loader = DataLoader(dataset, batch_size=16) |
| 287 |
|
| 288 |
model, optimizer, data_loader = accelerator.prepare(model, optimizer, data_loader) |
| 289 |
|
| 290 |
# Training loop |
| 291 |
for data, targets in data_loader: |
| 292 |
outputs = model(data) |
| 293 |
loss = criterion(outputs, targets) |
| 294 |
accelerator.backward(loss) |
| 295 |
optimizer.step() |
| 296 |
optimizer.zero_grad() |
| 297 |
``` |
| 298 |
|
| 299 |
### comm_state_option |
| 300 |
|
| 301 |
`comm_state_option` allows you to pass additional state information required by certain communication hooks. This is particularly useful for stateful hooks like `PowerSGD`, which require maintaining hyperparameters and internal states across training steps. Below is an example showcasing the use of `comm_state_option` with the `PowerSGD` hook. |
| 302 |
|
| 303 |
```python |
| 304 |
from accelerate import Accelerator, DDPCommunicationHookType, DistributedDataParallelKwargs |
| 305 |
import torch |
| 306 |
|
| 307 |
class MyModel(torch.nn.Module): |
| 308 |
def __init__(self): |
| 309 |
super().__init__() |
| 310 |
self.layer = torch.nn.Linear(10, 10) |
| 311 |
|
| 312 |
def forward(self, x): |
| 313 |
return self.layer(x) |
| 314 |
|
| 315 |
# DDP Communication Hook setup |
| 316 |
ddp_kwargs = DistributedDataParallelKwargs( |
| 317 |
comm_hook=DDPCommunicationHookType.POWER_SGD, |
| 318 |
comm_state_option={"matrix_approximation_rank": 2} |
| 319 |
) |
| 320 |
accelerator = Accelerator(kwargs_handlers=[ddp_kwargs]) |
| 321 |
|
| 322 |
model = MyModel() |
| 323 |
optimizer = torch.optim.Adam(model.parameters()) |
| 324 |
data_loader = DataLoader(dataset, batch_size=16) |
| 325 |
|
| 326 |
model, optimizer, data_loader = accelerator.prepare(model, optimizer, data_loader) |
| 327 |
|
| 328 |
# Training loop |
| 329 |
for data, targets in data_loader: |
| 330 |
outputs = model(data) |
| 331 |
loss = criterion(outputs, targets) |
| 332 |
accelerator.backward(loss) |
| 333 |
optimizer.step() |
| 334 |
optimizer.zero_grad() |
| 335 |
``` |
| 336 |
|
| 337 |
For more advanced usage and additional hooks, refer to the [PyTorch DDP Communication Hooks documentation](https://pytorch.org/docs/stable/ddp_comm_hooks.html). |