Debian Codegraph @

docs/source/concept_guides/gradient_synchronization.md

raw
1 <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
3 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4 the License. You may obtain a copy of the License at
5
6 http://www.apache.org/licenses/LICENSE-2.0
7
8 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9 an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10 specific language governing permissions and limitations under the License.
11
12 ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13 rendered properly in your Markdown viewer.
14 -->
15
16 # Gradient synchronization
17
18 PyTorch's distributed module operates by communicating back and forth between all of the GPUs in your system.
19 This communication takes time, and ensuring all processes know the states of each other happens at particular triggerpoints
20 when using the `ddp` module.
21
22 These triggerpoints are added to the PyTorch model, specifically their `forward()` and `backward()` methods.
23 This happens when the model is wrapped with `DistributedDataParallel`:
24 ```python
25 import torch.nn as nn
26 from torch.nn.parallel import DistributedDataParallel
27
28 model = nn.Linear(10, 10)
29 ddp_model = DistributedDataParallel(model)
30 ```
31 In Accelerate this conversion happens automatically when calling [`~Accelerator.prepare`] and passing in your model.
32
33 ```diff
34 + from accelerate import Accelerator
35 + accelerator = Accelerator()
36 import torch.nn as nn
37 - from torch.nn.parallel import DistributedDataParallel
38
39 model = nn.Linear(10,10)
40 + model = accelerator.prepare(model)
41 ```
42
43 ## The slowdown in gradient accumulation
44
45 You now understand that PyTorch adds hooks to the `forward` and `backward` method of your PyTorch model when
46 training in a distributed setup. But how does this risk slowing down your code?
47
48 In DDP (distributed data parallel), the specific order in which processes are performed and ran are expected
49 at specific points and these must also occur at roughly the same time before moving on.
50
51 The most direct example is when you update model parameters through
52 `optimizer.step()`.
53 Without gradient accumulation, all instances of the model need to have updated
54 their gradients computed, collated, and updated before moving on to the next
55 batch of data.
56 When performing gradient accumulation, you accumulate `n` loss gradients and
57 skip `optimizer.step()` until `n` batches have been reached. As all training
58 processes only need to synchronize by the time `optimizer.step()` is called,
59 without any modification to your training step, this needless inter-process
60 communication can cause a significant slowdown.
61
62 How can you avoid this overhead?
63
64 ## Solving the slowdown problem
65
66 Since you are skipping model parameter updates when training on these batches, their gradients do not need to be synchronized until the point where `optimizer.step()` is actually called.
67 PyTorch cannot automagically tell when you need to do this, but they do provide a tool to help through the [`no_sync`](https://pytorch.org/docs/stable/generated/torch.nn.parallel.DistributedDataParallel.html#torch.nn.parallel.DistributedDataParallel.no_sync) context manager
68 that is added to your model after converting it to DDP.
69
70 Under this context manager, PyTorch will skip synchronizing the gradients when
71 `.backward()` is called, and the first call to `.backward()` outside this
72 context manager will trigger the synchronization. See an example below:
73 ```python
74 ddp_model, dataloader, optimizer = accelerator.prepare(model, dataloader, optimizer)
75
76 for index, batch in enumerate(dataloader):
77 inputs, targets = batch
78 # Trigger gradient synchronization on the last batch
79 if index != (len(dataloader) - 1):
80 with ddp_model.no_sync():
81 # Gradients only accumulate
82 outputs = ddp_model(inputs)
83 loss = loss_func(outputs)
84 accelerator.backward(loss)
85 else:
86 # Gradients finally sync
87 outputs = ddp_model(inputs)
88 loss = loss_func(outputs)
89 accelerator.backward(loss)
90 optimizer.step()
91 ```
92
93 In Accelerate to make this an API that can be called no matter the training device (though it may not do anything if you are not in a distributed system!),
94 `ddp_model.no_sync` gets replaced with [`~Accelerator.no_sync`] and operates the same way:
95
96 ```diff
97 ddp_model, dataloader, optimizer = accelerator.prepare(model, dataloader, optimizer)
98
99 for index, batch in enumerate(dataloader):
100 inputs, targets = batch
101 # Trigger gradient synchronization on the last batch
102 if index != (len(dataloader)-1):
103 - with ddp_model.no_sync():
104 + with accelerator.no_sync(model):
105 # Gradients only accumulate
106 outputs = ddp_model(inputs)
107 loss = loss_func(outputs, targets)
108 accelerator.backward(loss)
109 else:
110 # Gradients finally sync
111 outputs = ddp_model(inputs)
112 loss = loss_func(outputs)
113 accelerator.backward(loss)
114 optimizer.step()
115 optimizer.zero_grad()
116 ```
117
118 As you may expect, the [`~Accelerator.accumulate`] function wraps around this conditional check by keeping track of the current batch number, leaving you with the final
119 gradient accumulation API:
120
121 ```python
122 ddp_model, dataloader, optimizer = accelerator.prepare(model, dataloader, optimizer)
123
124 for batch in dataloader:
125 with accelerator.accumulate(model):
126 optimizer.zero_grad()
127 inputs, targets = batch
128 outputs = model(inputs)
129 loss = loss_function(outputs, targets)
130 accelerator.backward(loss)
131 optimizer.step()
132 optimizer.zero_grad()
133 ```
134
135 As a result, you should either use *`accelerator.accumulate` or `accelerator.no_sync`* when it comes to API choice.
136
137 ## Just how much of a slowdown is there, and easy mistakes you can make
138
139 To set up a realistic example, consider the following setup:
140
141 * Two single-GPU T4 nodes and one node with two GPUs
142 * Each GPU is a T4, and are hosted on GCP
143 * The script used is a modification of the [NLP Example](https://github.com/muellerzr/timing_experiments/blob/main/baseline.py) script
144 * Batch size per GPU is 16, and gradients are accumulated every 4 steps
145
146 All scripts are available in [this repository](https://github.com/muellerzr/timing_experiments).
147
148 If not careful about gradient synchronization and GPU communication, a *large* amount of time can be wasted
149 from when these GPUs communicate to each other during unnecessary periods.
150
151 By how much?
152
153 Reference:
154 - Baseline: uses no synchronization practices discussed here
155 - `no_sync` improperly: `no_sync` only around the `backward` call, not the `forward`
156 - `no_sync`: using the `no_sync` pattern properly
157 - `accumulate`: using [`~Accelerator.accumulate`] properly
158
159 Below are the average seconds per batch iterating over 29 batches of data for each setup on both a single node and on the dual-node setup:
160
161 | | Baseline | `no_sync` improperly | `no_sync` | `accumulate`|
162 | :---------: | :-------: | :------------------: | :-------: | :---------: |
163 | Multi-Node | 2±0.01s | 2.13±0.08s | **0.91±0.11s** | **0.91±0.11s** |
164 | Single Node | 0.50±0.01s | 0.50±0.01s | **0.41±0.015s** | **0.41±0.015s** |
165
166 As you can see, if you are not careful about how you set up your gradient synchronization, you can get upwards of more than a 2x slowdown during training!
167
168 If you are worried about making sure everything is done properly, we highly recommend utilizing the [`~Accelerator.accumulate`] function and passing in
169 `gradient_accumulation_steps` or `gradient_accumulation_plugin` to the [`Accelerator`] object so Accelerate can handle this for you.
170
171 ### `no_sync` requires additional GPU memory when using FSDP
172
173 Be aware that not syncing gradients can have adverse effects while performing FSDP training. As it has been warned in `torch`, the [`no_sync` context manager for FSDP](https://pytorch.org/docs/stable/fsdp.html#torch.distributed.fsdp.FullyShardedDataParallel.no_sync) will require additional memory.
174
175 Therefore in memory intensive situations while using FSDP, we recommend to set `sync_each_batch` to `True` in the [`~utils.GradientAccumulationPlugin`] to disable `no_sync`.
176
177 See the example below where we fine-tune Mixtral (47B parameters) on 8 A100-80GB GPUs. We see that even for a modest `gradient_accumulation_steps=2` we quickly go out-of-memory (OOM) if `no_sync` is enabled. Again, this is due to additional memory overheads due to FSDP's `no_sync`. However, if `no_sync` is disabled via `sync_each_batch=True`, then the memory consumption for `gradient_accumulation_steps=16` reverts to that of `gradient_accumulation_steps=1`.
178
179 | Model | `no_sync` (accum=1) | `no_sync` (accum=2) | `no_sync` disabled (accum=16)
180 | :-------------: | :-----------------: | :-----------------: | :-----------------:
181 mixtral 8x7B | 69G | OOM | 69G
182
183 > [!WARNING]
184 > Disabling `no_sync` means there _will be slowdown_ due the extra data syncs, as explained by the earlier sections of this guide.