Debian Codegraph @

docs/source/usage_guides/gradient_accumulation.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 # Performing gradient accumulation with Accelerate
17
18 Gradient accumulation is a technique where you can train on bigger batch sizes than
19 your machine would normally be able to fit into memory. This is done by accumulating gradients over
20 several batches, and only stepping the optimizer after a certain number of batches have been performed.
21
22 While technically standard gradient accumulation code would work fine in a distributed setup, it is not the most efficient
23 method for doing so and you may experience considerable slowdowns!
24
25 In this tutorial you will see how to quickly setup gradient accumulation and perform it with the utilities provided in Accelerate,
26 which can total to adding just one new line of code!
27
28 This example will use a very simplistic PyTorch training loop that performs gradient accumulation every two batches:
29
30 ```python
31 device = "cuda"
32 model.to(device)
33
34 gradient_accumulation_steps = 2
35
36 for index, batch in enumerate(training_dataloader):
37 inputs, targets = batch
38 inputs = inputs.to(device)
39 targets = targets.to(device)
40 outputs = model(inputs)
41 loss = loss_function(outputs, targets)
42 loss = loss / gradient_accumulation_steps
43 loss.backward()
44 if (index + 1) % gradient_accumulation_steps == 0:
45 optimizer.step()
46 scheduler.step()
47 optimizer.zero_grad()
48 ```
49
50 ## Converting it to Accelerate
51
52 First the code shown earlier will be converted to utilize Accelerate without the special gradient accumulation helper:
53
54 ```diff
55 + from accelerate import Accelerator
56 + accelerator = Accelerator()
57
58 + model, optimizer, training_dataloader, scheduler = accelerator.prepare(
59 + model, optimizer, training_dataloader, scheduler
60 + )
61
62 for index, batch in enumerate(training_dataloader):
63 inputs, targets = batch
64 - inputs = inputs.to(device)
65 - targets = targets.to(device)
66 outputs = model(inputs)
67 loss = loss_function(outputs, targets)
68 loss = loss / gradient_accumulation_steps
69 + accelerator.backward(loss)
70 if (index+1) % gradient_accumulation_steps == 0:
71 optimizer.step()
72 scheduler.step()
73 optimizer.zero_grad()
74 ```
75
76 <Tip warning={true}>
77
78 In its current state, this code is not going to perform gradient accumulation efficiently due to a process called gradient synchronization. Read more about that in the [Concepts tutorial](../concept_guides/gradient_synchronization)!
79
80 </Tip>
81
82 ## Letting Accelerate handle gradient accumulation
83
84 All that is left now is to let Accelerate handle the gradient accumulation for us. To do so you should pass in a `gradient_accumulation_steps` parameter to [`Accelerator`], dictating the number
85 of steps to perform before each call to `step()` and how to automatically adjust the loss during the call to [`~Accelerator.backward`]:
86
87 ```diff
88 from accelerate import Accelerator
89 - accelerator = Accelerator()
90 + accelerator = Accelerator(gradient_accumulation_steps=2)
91 ```
92
93 Alternatively, you can pass in a `gradient_accumulation_plugin` parameter to the [`Accelerator`] object's `__init__`, which will allow you to further customize the gradient accumulation behavior.
94 Read more about that in the [GradientAccumulationPlugin](../package_reference/accelerator#accelerate.utils.GradientAccumulationPlugin) docs.
95
96 From here you can use the [`~Accelerator.accumulate`] context manager from inside your training loop to automatically perform the gradient accumulation for you!
97 You just wrap it around the entire training part of our code:
98
99 ```diff
100 - for index, batch in enumerate(training_dataloader):
101 + for batch in training_dataloader:
102 + with accelerator.accumulate(model):
103 inputs, targets = batch
104 outputs = model(inputs)
105 ```
106
107 You can remove all the special checks for the step number and the loss adjustment:
108
109 ```diff
110 - loss = loss / gradient_accumulation_steps
111 accelerator.backward(loss)
112 - if (index+1) % gradient_accumulation_steps == 0:
113 optimizer.step()
114 scheduler.step()
115 optimizer.zero_grad()
116 ```
117
118 As you can see the [`Accelerator`] is able to keep track of the batch number you are on and it will automatically know whether to step through the prepared optimizer and how to adjust the loss.
119
120 <Tip>
121
122 Typically with gradient accumulation, you would need to adjust the number of steps to reflect the change in total batches you are
123 training on. Accelerate automagically does this for you by default. Behind the scenes we instantiate a [`GradientAccumulationPlugin`] configured to do this.
124
125 </Tip>
126
127 <Tip warning={true}>
128
129 The [`state.GradientState`] is sync'd with the active dataloader being iterated upon. As such it assumes naively that when we have reached the end of the dataloader everything will sync and a step will be performed. To disable this, set `sync_with_dataloader` to be `False` in the [`GradientAccumulationPlugin`]:
130
131 ```{python}
132 from accelerate import Accelerator
133 from accelerate.utils import GradientAccumulationPlugin
134
135 plugin = GradientAccumulationPlugin(sync_with_dataloader=False)
136 accelerator = Accelerator(..., gradient_accumulation_plugin=plugin)
137 ```
138
139 </Tip>
140
141 ## The finished code
142
143 Below is the finished implementation for performing gradient accumulation with Accelerate
144
145 ```python
146 from accelerate import Accelerator
147 accelerator = Accelerator(gradient_accumulation_steps=2)
148 model, optimizer, training_dataloader, scheduler = accelerator.prepare(
149 model, optimizer, training_dataloader, scheduler
150 )
151 for batch in training_dataloader:
152 with accelerator.accumulate(model):
153 inputs, targets = batch
154 outputs = model(inputs)
155 loss = loss_function(outputs, targets)
156 accelerator.backward(loss)
157 optimizer.step()
158 scheduler.step()
159 optimizer.zero_grad()
160 ```
161
162 <Tip warning={true}>
163
164 It's important that **only one forward/backward** should be done inside the context manager `with accelerator.accumulate(model)`.
165
166 </Tip>
167
168
169 To learn more about what magic this wraps around, read the [Gradient Synchronization concept guide](../concept_guides/gradient_synchronization)
170
171
172 ## Self-contained example
173
174 Here is a self-contained example that you can run to see gradient accumulation in action with Accelerate:
175
176 ```python
177 import torch
178 import copy
179 from accelerate import Accelerator
180 from accelerate.utils import set_seed
181 from torch.utils.data import TensorDataset, DataLoader
182
183 # seed
184 set_seed(0)
185
186 # define toy inputs and labels
187 x = torch.tensor([1., 2., 3., 4., 5., 6., 7., 8.])
188 y = torch.tensor([2., 4., 6., 8., 10., 12., 14., 16.])
189 gradient_accumulation_steps = 4
190 per_device_batch_size = len(x) // gradient_accumulation_steps
191
192 # define dataset and dataloader
193 dataset = TensorDataset(x, y)
194 dataloader = DataLoader(dataset, batch_size=per_device_batch_size)
195
196 # define model, optimizer and loss function
197 class SimpleLinearModel(torch.nn.Module):
198 def __init__(self):
199 super(SimpleLinearModel, self).__init__()
200 self.weight = torch.nn.Parameter(torch.zeros((1, 1)))
201
202 def forward(self, inputs):
203 return inputs @ self.weight
204
205 model = SimpleLinearModel()
206 model_clone = copy.deepcopy(model)
207 criterion = torch.nn.MSELoss()
208 model_optimizer = torch.optim.SGD(model.parameters(), lr=0.02)
209 accelerator = Accelerator(gradient_accumulation_steps=gradient_accumulation_steps)
210 model, model_optimizer, dataloader = accelerator.prepare(model, model_optimizer, dataloader)
211 model_clone_optimizer = torch.optim.SGD(model_clone.parameters(), lr=0.02)
212 print(f"initial model weight is {model.weight.mean().item():.5f}")
213 print(f"initial model weight is {model_clone.weight.mean().item():.5f}")
214 for i, (inputs, labels) in enumerate(dataloader):
215 with accelerator.accumulate(model):
216 inputs = inputs.view(-1, 1)
217 print(i, inputs.flatten())
218 labels = labels.view(-1, 1)
219 outputs = model(inputs)
220 loss = criterion(outputs, labels)
221 accelerator.backward(loss)
222 model_optimizer.step()
223 model_optimizer.zero_grad()
224 loss = criterion(x.view(-1, 1) @ model_clone.weight, y.view(-1, 1))
225 model_clone_optimizer.zero_grad()
226 loss.backward()
227 model_clone_optimizer.step()
228 print(f"w/ accumulation, the final model weight is {model.weight.mean().item():.5f}")
229 print(f"w/o accumulation, the final model weight is {model_clone.weight.mean().item():.5f}")
230 ```
231 ```
232 initial model weight is 0.00000
233 initial model weight is 0.00000
234 0 tensor([1., 2.])
235 1 tensor([3., 4.])
236 2 tensor([5., 6.])
237 3 tensor([7., 8.])
238 w/ accumulation, the final model weight is 2.04000
239 w/o accumulation, the final model weight is 2.04000
240 ```
241
242 ## Gradient accumulation on training samples of variable size
243
244 As was pointed out in this [blog-post](https://huggingface.co/blog/gradient_accumulation), which points out a common error that occurs when performing gradient accumulation on training samples of variable size:
245
246 > [...] for gradient accumulation across token-level tasks like causal LM training, the correct loss should be computed by the **total loss across all batches in a gradient accumulation step** divided by the **total number of all non padding tokens in those batches**. This is not the same as the average of the per-batch loss values.
247
248 In other words, some adjustments must be made on losses that operate on a token-level basis.
249
250 ### Skeleton code
251
252 ```python
253 from accelerate import Accelerator
254 import math
255 import contextlib
256
257 gradient_accumulation_steps = 2
258 accelerator = Accelerator(gradient_accumulation_steps=gradient_accumulation_steps)
259 model, optimizer, training_dataloader, scheduler = accelerator.prepare(
260 model, optimizer, training_dataloader, scheduler
261 )
262
263 training_iterator = iter(training_dataloader)
264 num_samples_in_epoch = len(training_dataloader)
265 remainder = num_samples_in_epoch % gradient_accumulation_steps
266 remainder = remainder if remainder != 0 else gradient_accumulation_steps
267 total_updates = math.ceil(num_samples_in_epoch / gradient_accumulation_steps)
268
269
270 total_batched_samples = 0
271 for update_step in range(total_updates):
272 # In order to correctly the total number of non-padded tokens on which we'll compute the cross-entropy loss
273 # we need to pre-load the full local batch - i.e the next per_device_batch_size * accumulation_steps samples
274 batch_samples = []
275 num_batches_in_step = gradient_accumulation_steps if update_step != (total_updates - 1) else remainder
276 for _ in range(num_batches_in_step):
277 batch_samples += [next(training_iterator)]
278
279 # get local num items in batch
280 num_items_in_batch = sum([(batch["labels"].ne(-100)).sum() for batch in batch_samples])
281 # to compute it correctly in a multi-device DDP training, we need to gather the total number of items in the full batch.
282 num_items_in_batch = accelerator.gather(num_items_in_batch).sum().item()
283
284 for i, batch in enumerate(batch_samples):
285 # if we perform gradient accumulation in a multi-devices set-up, we want to avoid unnecessary communications when accumulating
286 # cf: https://muellerzr.github.io/blog/gradient_accumulation.html
287 if (i < len(batch_samples) - 1 and accelerator.num_processes > 1):
288 ctx = model.no_sync
289 else:
290 ctx = contextlib.nullcontext
291
292 total_batched_samples += 1
293
294 with ctx():
295 inputs, targets = batch
296 outputs = model(inputs)
297 loss = loss_function(outputs, targets) # the loss function should sum over samples rather than averaging
298
299 # We multiply by num_processes because the DDP calculates the average gradient across all devices whereas dividing by num_items_in_batch already takes into account all devices
300 # Same reason for gradient_accumulation_steps, but this times it's Accelerate that calculate the average gradient across the accumulated steps
301 loss = (loss * gradient_accumulation_steps * accelerator.num_processes) / num_items_in_batch
302
303 accelerator.backward(loss)
304
305 # Sync gradients and perform optimization steps once every gradient_accumulation_steps
306 optimizer.step()
307 scheduler.step()
308 optimizer.zero_grad()
309 ```
310
311 ### Self-contained causal LM example
312
313 ```py
314 import torch
315 import copy
316 from accelerate import Accelerator
317 from accelerate.utils import set_seed
318 from accelerate.logging import get_logger
319 from torch.utils.data import Dataset, DataLoader
320 import math
321 import contexlib
322
323 # seed
324 set_seed(0)
325 logger = get_logger(__name__)
326
327 class MyDataset(Dataset):
328 def __init__(self, num_samples):
329 super().__init__()
330 self.len = num_samples
331
332 def __getitem__(self, index):
333 input_ids = torch.arange(1, index+2, dtype=torch.float32)
334 labels = torch.remainder(input_ids, 2)
335 return {"input_ids": input_ids, "labels": labels}
336
337 def __len__(self):
338 return self.len
339
340 def collate_fn(features):
341 input_ids = torch.nn.utils.rnn.pad_sequence([f["input_ids"] for f in features], batch_first=True, padding_value=-100)
342 labels = torch.nn.utils.rnn.pad_sequence([f["labels"] for f in features], batch_first=True, padding_value=-100)
343 return {"input_ids": input_ids[..., None], "labels": labels[..., None]}
344
345 # define toy inputs and labels
346 gradient_accumulation_steps = 2
347 per_device_batch_size = 4
348
349 # define accelerator
350 accelerator = Accelerator(gradient_accumulation_steps=gradient_accumulation_steps)
351
352 # define dataset and dataloader
353 # for this toy example, we'll compute gradient descent over one single global batch
354 dataset = MyDataset(per_device_batch_size*gradient_accumulation_steps*accelerator.num_processes)
355 dataloader = DataLoader(dataset, batch_size=per_device_batch_size, collate_fn=collate_fn)
356
357 # define model, model_optimizer and loss function
358 model = torch.nn.Linear(1, 2, bias=False)
359 model_clone = copy.deepcopy(model)
360 criterion = torch.nn.CrossEntropyLoss(reduction="sum") # must sum over samples rather than averaging
361 model_optimizer = torch.optim.SGD(model.parameters(), lr=0.08)
362
363
364 logger.warning(f"initial model weight is {model.weight.detach().cpu().squeeze()}")
365 logger.warning(f"initial model clone weight is {model_clone.weight.detach().cpu().squeeze()}")
366
367 # prepare artifacts - accelerator handles device placement and dataloader splitting
368 model, model_optimizer = accelerator.prepare(model, model_optimizer)
369 dataloader = accelerator.prepare_data_loader(dataloader, device_placement=True)
370 training_iterator = iter(dataloader)
371
372 num_samples_in_epoch = len(dataloader)
373 remainder = num_samples_in_epoch % gradient_accumulation_steps
374 remainder = remainder if remainder != 0 else gradient_accumulation_steps
375 total_gradient_updates = math.ceil(num_samples_in_epoch / gradient_accumulation_steps)
376
377 total_batched_samples = 0
378 for update_step in range(total_gradient_updates):
379 # In order to correctly the total number of non-padded tokens on which we'll compute the cross-entropy loss
380 # we need to pre-load the full local batch - i.e the next per_device_batch_size * accumulation_steps samples
381 batch_samples = []
382 num_batches_in_step = gradient_accumulation_steps if update_step != (total_gradient_updates - 1) else remainder
383 for _ in range(num_batches_in_step):
384 batch_samples += [next(training_iterator)]
385
386 # get local num items in batch
387 local_num_items_in_batch = sum([(batch["labels"].ne(-100)).sum() for batch in batch_samples])
388 logger.warning(f"Step {update_step} - Device {accelerator.process_index} - num items in the local batch {local_num_items_in_batch}", main_process_only=False)
389
390 # to compute it correctly in a multi-device DDP training, we need to gather the total number of items in the full batch.
391 num_items_in_batch = accelerator.gather(local_num_items_in_batch).sum().item()
392 logger.warning(f"Total num items {num_items_in_batch}")
393
394 for i, batch in enumerate(batch_samples):
395 inputs, labels = batch["input_ids"], batch["labels"]
396 total_batched_samples += 1
397 # if we perform gradient accumulation in a multi-devices set-up, we want to avoid unnecessary communications when accumulating
398 # cf: https://muellerzr.github.io/blog/gradient_accumulation.html
399 if (i < len(batch_samples) - 1 and accelerator.num_processes > 1):
400 ctx = model.no_sync
401 else:
402 ctx = contextlib.nullcontext
403 with ctx():
404
405 outputs = model(inputs)
406 loss = criterion(outputs.view(-1, 2), labels.view(-1).to(torch.int64))
407
408 # We multiply by num_processes because the DDP calculates the average gradient across all devices whereas dividing by num_items_in_batch already takes into account all devices
409 # Same reason for gradient_accumulation_steps, but this times it's Accelerate that calculate the average gradient across the accumulated steps
410 loss = (loss * gradient_accumulation_steps * accelerator.num_processes) / num_items_in_batch
411 accelerator.backward(loss)
412 model_optimizer.step()
413 model_optimizer.zero_grad()
414
415
416 logger.warning(f"Device {accelerator.process_index} - w/ accumulation, the final model weight is {accelerator.unwrap_model(model).weight.detach().cpu().squeeze()}", main_process_only=False)
417
418 # We know do the same operation but on a single device and without gradient accumulation
419
420 if accelerator.is_main_process:
421 # prepare one single entire batch
422 dataloader = DataLoader(dataset, batch_size=len(dataset), collate_fn=collate_fn)
423 full_batch_without_accum = next(iter(dataloader))
424 total_inputs, total_labels = full_batch_without_accum["input_ids"], full_batch_without_accum["labels"]
425 model_clone_optimizer = torch.optim.SGD(model_clone.parameters(), lr=0.08)
426
427 # train the cloned model
428 loss = torch.nn.CrossEntropyLoss(reduction="mean")(model_clone(total_inputs).view(-1, 2), total_labels.view(-1).to(torch.int64))
429 model_clone_optimizer.zero_grad()
430 loss.backward()
431 model_clone_optimizer.step()
432
433 # We should have the same final weights.
434 logger.warning(f"w/o accumulation, the final model weight is {model_clone.weight.detach().cpu().squeeze()}")
435
436 ```
437
438 Results on a single device - gradient accumulation steps set to 1 and batch_size set to 8:
439 ```
440 initial model weight is tensor([-0.0075, 0.5364])
441 initial model clone weight is tensor([-0.0075, 0.5364])
442 Step 0 - Device 0 - num items in the local batch 36
443 Total num items 36
444 Device 0 - w/ accumulation, the final model weight is tensor([0.0953, 0.4337])
445 w/o accumulation, the final model weight is tensor([0.0953, 0.4337])
446 ```
447
448 Results on a two devices set-up - gradient accumulation steps set to 2 and batch_size set to 4.
449 ```
450 initial model weight is tensor([-0.0075, 0.5364])
451 initial model clone weight is tensor([-0.0075, 0.5364])
452 Step 0 - Device 0 - num items in the local batch 52
453 Step 0 - Device 1 - num items in the local batch 84
454 Total num items 136
455 Device 1 - w/ accumulation, the final model weight is tensor([0.2117, 0.3172])
456 Device 0 - w/ accumulation, the final model weight is tensor([0.2117, 0.3172])
457 w/o accumulation, the final model weight is tensor([0.2117, 0.3172])
458 ```
459
460 ### To go further:
461
462 Please find a complete example script on a real world training run in the examples folder at the path [`accelerate/examples/by_feature/gradient_accumulation_for_autoregressive_models.py`](https://github.com/huggingface/accelerate/blob/main/examples/by_feature/gradient_accumulation_for_autoregressive_models.py).
463
464 Running it on several training configurations with constant global batch size equal to 32 gives the following graph:
465
466 <div style="text-align: center">
467 <img src="https://huggingface.co/datasets/hf-audio/gradient_accumulation_example/resolve/main/training_losses.png">
468 </div>
469
470 Note that the training losses are exactly the same up to training step 20. The small deviation after this training step occurs at the very end of the first epoch, because, by [default](https://huggingface.co/docs/accelerate/en/package_reference/torch_wrappers#accelerate.data_loader.prepare_data_loader.even_batches), the dataloader duplicates the samples at the beginning of the dataset when the total batch size doesn't exactly divide the dataset.