Debian Codegraph @

docs/source/basic_tutorials/migration.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 # Add Accelerate to your code
17
18 Each distributed training framework has its own way of doing things which can require writing a lot of custom code to adapt it to your PyTorch training code and training environment. Accelerate offers a friendly way to interface with these distributed training frameworks without having to learn the specific details of each one. Accelerate takes care of those details for you, so you can focus on the training code and scale it to any distributed training environment.
19
20 In this tutorial, you'll learn how to adapt your existing PyTorch code with Accelerate and get you on your way toward training on distributed systems with ease! You'll start with a basic PyTorch training loop (it assumes all the training objects like `model` and `optimizer` have been set up already) and progressively integrate Accelerate into it.
21
22 ```python
23 device = "cuda"
24 model.to(device)
25
26 for batch in training_dataloader:
27 optimizer.zero_grad()
28 inputs, targets = batch
29 inputs = inputs.to(device)
30 targets = targets.to(device)
31 outputs = model(inputs)
32 loss = loss_function(outputs, targets)
33 loss.backward()
34 optimizer.step()
35 scheduler.step()
36 ```
37
38 ## Accelerator
39
40 The [`Accelerator`] is the main class for adapting your code to work with Accelerate. It knows about the distributed setup you're using such as the number of different processes and your hardware type. This class also provides access to many of the necessary methods for enabling your PyTorch code to work in any distributed training environment and for managing and executing processes across devices.
41
42 That's why you should always start by importing and creating an [`Accelerator`] instance in your script.
43
44 ```python
45 from accelerate import Accelerator
46
47 accelerator = Accelerator()
48 ```
49
50 The [`Accelerator`] also knows which device to move your PyTorch objects to, so it is recommended to let Accelerate handle this for you.
51
52 ```diff
53 - device = "cuda"
54 + device = accelerator.device
55 model.to(device)
56 ```
57
58 ## Prepare PyTorch objects
59
60 Next, you need to prepare your PyTorch objects (model, optimizer, scheduler, etc.) for distributed training. The [`~Accelerator.prepare`] method takes care of placing your model in the appropriate container (like single GPU or multi-GPU) for your training setup, adapting the optimizer and scheduler to use Accelerate's [`~optimizer.AcceleratedOptimizer`] and [`~scheduler.AcceleratedScheduler`], and creating a new dataloader that can be sharded across processes.
61
62 > [!TIP]
63 > Accelerate only prepares objects that inherit from their respective PyTorch classes such as `torch.optim.Optimizer`.
64
65 The PyTorch objects are returned in the same order they're sent.
66
67 ```py
68 model, optimizer, training_dataloader, scheduler = accelerator.prepare(
69 model, optimizer, training_dataloader, scheduler
70 )
71 ```
72
73 ## Training loop
74
75 Finally, remove the `to(device)` calls to the inputs and targets in the training loop because Accelerate's DataLoader classes automatically places them on the right device. You should also replace the usual `backward()` pass with Accelerate's [`~Accelerator.backward`] method which scales the gradients for you and uses the appropriate `backward()` method depending on your distributed setup (for example, DeepSpeed or Megatron).
76
77 ```diff
78 - inputs = inputs.to(device)
79 - targets = targets.to(device)
80 outputs = model(inputs)
81 loss = loss_function(outputs, targets)
82 - loss.backward()
83 + accelerator.backward(loss)
84 ```
85
86 Put everything together and your new Accelerate training loop should now look like this!
87
88 ```python
89 from accelerate import Accelerator
90 accelerator = Accelerator()
91
92 device = accelerator.device
93 model, optimizer, training_dataloader, scheduler = accelerator.prepare(
94 model, optimizer, training_dataloader, scheduler
95 )
96
97 for batch in training_dataloader:
98 optimizer.zero_grad()
99 inputs, targets = batch
100 outputs = model(inputs)
101 loss = loss_function(outputs, targets)
102 accelerator.backward(loss)
103 optimizer.step()
104 scheduler.step()
105 ```
106
107 ## Training features
108
109 Accelerate offers additional features - like gradient accumulation, gradient clipping, mixed precision training and more - you can add to your script to improve your training run. Let's explore these three features.
110
111 ### Gradient accumulation
112
113 Gradient accumulation enables you to train on larger batch sizes by accumulating the gradients over multiple batches before updating the weights. This can be useful for getting around memory limitations. To enable this feature in Accelerate, specify the `gradient_accumulation_steps` parameter in the [`Accelerator`] class and add the [`~Accelerator.accumulate`] context manager to your script.
114
115 ```diff
116 + accelerator = Accelerator(gradient_accumulation_steps=2)
117 model, optimizer, training_dataloader = accelerator.prepare(model, optimizer, training_dataloader)
118
119 for input, label in training_dataloader:
120 + with accelerator.accumulate(model):
121 predictions = model(input)
122 loss = loss_function(predictions, label)
123 accelerator.backward(loss)
124 optimizer.step()
125 scheduler.step()
126 optimizer.zero_grad()
127 ```
128
129 ### Gradient clipping
130
131 Gradient clipping is a technique to prevent "exploding gradients", and Accelerate offers:
132
133 * [`~Accelerator.clip_grad_value_`] to clip gradients to a minimum and maximum value
134 * [`~Accelerator.clip_grad_norm_`] for normalizing gradients to a certain value
135
136 ### Mixed precision
137
138 Mixed precision accelerates training by using a lower precision data type like fp16 (half-precision) to calculate the gradients. For the best performance with Accelerate, the loss should be computed inside your model (like in Transformers models) because computations outside of the model are computed in full precision.
139
140 Set the mixed precision type to use in the [`Accelerator`], and then use the [`~Accelerator.autocast`] context manager to automatically cast the values to the specified data type.
141
142 > [!WARNING]
143 > Accelerate enables automatic mixed precision, so [`~Accelerator.autocast`] is only needed if there are other mixed precision operations besides those performed on loss by [`~Accelerator.backward`] which already handles the scaling.
144
145 ```diff
146 + accelerator = Accelerator(mixed_precision="fp16")
147 + with accelerator.autocast():
148 loss = complex_loss_function(outputs, target)
149 ```
150
151 ## Save and load
152
153 Accelerate can also save and load a *model* once training is complete or you can also save the model and optimizer *state* which could be useful for resuming training.
154
155 ### Model
156
157 Once all processes are complete, unwrap the model with the [`~Accelerator.unwrap_model`] method before saving it because the [`~Accelerator.prepare`] method wrapped your model into the proper interface for distributed training. If you don't unwrap the model, saving the model state dictionary also saves any potential extra layers from the larger model and you won't be able to load the weights back into your base model.
158
159 You should use the [`~Accelerator.save_model`] method to unwrap and save the model state dictionary. This method can also save a model into sharded checkpoints or into the [safetensors](https://hf.co/docs/safetensors/index) format.
160
161 <hfoptions id="save">
162 <hfoption id="single checkpoint">
163
164 ```py
165 accelerator.wait_for_everyone()
166 accelerator.save_model(model, save_directory)
167 ```
168
169 <Tip>
170
171 For models from the [Transformers](https://hf.co/docs/transformers/index) library, save the model with the [`~transformers.PreTrainedModel.save_pretrained`] method so that it can be reloaded with the [`~transformers.PreTrainedModel.from_pretrained`] method.
172
173 ```py
174 from transformers import AutoModel
175
176 unwrapped_model = accelerator.unwrap_model(model)
177 unwrapped_model.save_pretrained(
178 "path/to/my_model_directory",
179 is_main_process=accelerator.is_main_process,
180 save_function=accelerator.save,
181 )
182
183 model = AutoModel.from_pretrained("path/to/my_model_directory")
184 ```
185
186 </Tip>
187
188 To load your weights, use the [`~Accelerator.unwrap_model`] method to unwrap the model first before loading the weights. All model parameters are references to tensors, so this loads your weights inside `model`.
189
190 ```py
191 unwrapped_model = accelerator.unwrap_model(model)
192 path_to_checkpoint = os.path.join(save_directory,"pytorch_model.bin")
193 unwrapped_model.load_state_dict(torch.load(path_to_checkpoint))
194 ```
195
196 </hfoption>
197 <hfoption id="sharded checkpoint">
198
199 Set `safe_serialization=True` to save the model in the safetensor format.
200
201 ```py
202 accelerator.wait_for_everyone()
203 accelerator.save_model(model, save_directory, max_shard_size="1GB", safe_serialization=True)
204 ```
205
206 To load a sharded checkpoint or a safetensor formatted checkpoint, use the [`~accelerate.load_checkpoint_in_model`] method. This method allows you to load a checkpoint onto a specific device.
207
208 ```py
209 load_checkpoint_in_model(unwrapped_model, save_directory, device_map={"":device})
210 ```
211
212 </hfoption>
213 </hfoptions>
214
215 ### State
216
217 During training, you may want to save the current state of the model, optimizer, random generators, and potentially learning rate schedulers so they can be restored in the *same script*. You should add the [`~Accelerator.save_state`] and [`~Accelerator.load_state`] methods to your script to save and load states.
218
219 To further customize where and how states are saved through [`~Accelerator.save_state`], use the [`~utils.ProjectConfiguration`] class. For example, if `automatic_checkpoint_naming` is enabled, each saved checkpoint is stored at `Accelerator.project_dir/checkpoints/checkpoint_{checkpoint_number}`.
220
221 Any other stateful items to be stored should be registered with the [`~Accelerator.register_for_checkpointing`] method so they can be saved and loaded. Every object passed to this method to be stored must have a `load_state_dict` and `state_dict` function.
222
223 > [!TIP]
224 > If you have [`torchdata>=0.8.0`](https://github.com/pytorch/data/tree/main) installed, you can additionally pass `use_stateful_dataloader=True` into your [`~utils.DataLoaderConfiguration`]. This extends Accelerate's DataLoader classes with a `load_state_dict` and `state_dict` function, and makes it so `Accelerator.save_state` and `Accelerator.load_state` also track how far into the training dataset it has read when persisting the model.