Debian Codegraph @

docs/source/concept_guides/big_model_inference.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 # Loading big models into memory
17
18 When loading a pre-trained model in PyTorch, the usual workflow looks like this:
19
20 ```py
21 import torch
22
23 my_model = ModelClass(...)
24 state_dict = torch.load(checkpoint_file)
25 my_model.load_state_dict(state_dict)
26 ```
27
28 In plain English, those steps are:
29 1. Create the model with randomly initialized weights
30 2. Load the model weights (in a dictionary usually called a state dict) from the disk
31 3. Load those weights inside the model
32
33 While this works very well for regularly sized models, this workflow has some clear limitations when we deal with a huge model: in step 1, we load a full version of the model in RAM, and spend some time randomly initializing the weights (which will be discarded in step 3). In step 2, we load another full version of the model in RAM, with the pre-trained weights. If you're loading a model with 6 billion parameters, this means you will need 24GB of RAM for each copy of the model, so 48GB in total (half of it to load the model in FP16).
34
35 <Tip warning={true}>
36
37 This API is quite new and still in its experimental stage. While we strive to provide a stable API, it's possible some small parts of the public API will change in the future.
38
39 </Tip>
40
41 ## How the Process Works: A Quick Overview
42
43 <Youtube id="MWCSGj9jEAo" />
44
45 ## How the Process Works: Working with Code
46
47 ### Instantiating an empty model
48
49 The first tool Accelerate introduces to help with big models is a context manager [`init_empty_weights`] that helps you initialize a model without using any RAM so that step 1 can be done on models of any size. Here is how it works:
50
51 ```py
52 from accelerate import init_empty_weights
53
54 with init_empty_weights():
55 my_model = ModelClass(...)
56 ```
57
58 For instance:
59
60 ```py
61 with init_empty_weights():
62 model = nn.Sequential(*[nn.Linear(10000, 10000) for _ in range(1000)])
63 ```
64
65 initializes an empty model with a bit more than 100B parameters. Behind the scenes, this relies on the meta device introduced in PyTorch 1.9. During the initialization under the context manager, each time a parameter is created, it is instantly moved to that device.
66
67 <Tip warning={true}>
68
69 You can't move a model initialized like this on CPU or another device directly, since it doesn't have any data. It's also very likely that a forward pass with that empty model will fail, as not all operations are supported on the meta device.
70
71 </Tip>
72
73 ### Sharded checkpoints
74
75 It's possible your model is so big that even a single copy won't fit in RAM. That doesn't mean it can't be loaded: if you have one or several GPUs, this is more memory available to store your model. In this case, it's better if your checkpoint is split into several smaller files that we call checkpoint shards.
76
77 Accelerate will handle sharded checkpoints as long as you follow the following format: your checkpoint should be in a folder, with several files containing the partial state dicts, and there should be an index in the JSON format that contains a dictionary mapping parameter names to the file containing their weights. You can easily shard your model with [`~Accelerator.save_model`]. For instance, we could have a folder containing:
78
79 ```bash
80 first_state_dict.bin
81 index.json
82 second_state_dict.bin
83 ```
84
85 with index.json being the following file:
86
87 ```
88 {
89 "linear1.weight": "first_state_dict.bin",
90 "linear1.bias": "first_state_dict.bin",
91 "linear2.weight": "second_state_dict.bin",
92 "linear2.bias": "second_state_dict.bin"
93 }
94 ```
95
96 and `first_state_dict.bin` containing the weights for `"linear1.weight"` and `"linear1.bias"`, `second_state_dict.bin` the ones for `"linear2.weight"` and `"linear2.bias"`
97
98 ### Loading weights
99
100 The second tool Accelerate introduces is a function [`load_checkpoint_and_dispatch`], that will allow you to load a checkpoint inside your empty model. This supports full checkpoints (a single file containing the whole state dict) as well as sharded checkpoints. It will also automatically dispatch those weights across the devices you have available (GPUs, CPU RAM), so if you are loading a sharded checkpoint, the maximum RAM usage will be the size of the biggest shard.
101
102 If you want to use big model inference with Transformers models, check out this [documentation](https://huggingface.co/docs/transformers/main/en/main_classes/model#large-model-loading).
103
104 Here is how we can use this to load the [GPT2-1.5B](https://huggingface.co/marcsun13/gpt2-xl-linear-sharded) model.
105
106 Let's download the sharded version of this model.
107
108 ```bash
109 pip install huggingface_hub
110 ```
111
112 ```py
113 from huggingface_hub import snapshot_download
114 checkpoint = "marcsun13/gpt2-xl-linear-sharded"
115 weights_location = snapshot_download(repo_id=checkpoint)
116 ```
117
118 In order to initialize the model, we will use the library minGPT.
119
120 ```bash
121 git clone https://github.com/karpathy/minGPT.git
122 pip install minGPT/
123 ```
124
125 ```py
126 from accelerate import init_empty_weights
127 from mingpt.model import GPT
128
129 model_config = GPT.get_default_config()
130 model_config.model_type = 'gpt2-xl'
131 model_config.vocab_size = 50257
132 model_config.block_size = 1024
133
134 with init_empty_weights():
135 model = GPT(model_config)
136 ```
137
138 Then, load the checkpoint we just downloaded with:
139
140 ```py
141 from accelerate import load_checkpoint_and_dispatch
142
143 model = load_checkpoint_and_dispatch(
144 model, checkpoint=weights_location, device_map="auto", no_split_module_classes=['Block']
145 )
146 ```
147
148 By passing `device_map="auto"`, we tell Accelerate to determine automatically where to put each layer of the model depending on the available resources:
149 - first, we use the maximum space available on the GPU(s)
150 - if we still need space, we store the remaining weights on the CPU
151 - if there is not enough RAM, we store the remaining weights on the hard drive as memory-mapped tensors
152
153
154 #### `no_split_module_classes`
155
156 This parameter will indicate that some of the modules with the name `"Block"` should not be split across different devices. You should set here all blocks that
157 include a residual connection of some kind.
158
159
160 #### The `device_map`
161
162 You can see the `device_map` that Accelerate picked by accessing the `hf_device_map` attribute of your model:
163
164 ```py
165 model.hf_device_map
166 ```
167
168 ```python out
169 {'transformer.wte': 0,
170 'transformer.wpe': 0,
171 'transformer.drop': 0,
172 'transformer.h.0': 0,
173 ...
174 'transformer.h.21': 0,
175 'transformer.h.22': 1,
176 'transformer.h.23': 1,
177 'transformer.h.24': 1,
178 ...
179 'transformer.h.47': 1,
180 'transformer.ln_f': 1,
181 'lm_head': 1}
182 ```
183
184 It's fully possible to create your own device map for the layers to use as well, specifying the GPU device to use (a number), `"cpu"`, or `"disk"` and pass this in:
185
186 ```python
187 device_map = {
188 "transformer.wte": "cpu",
189 "transformer.wpe": 0,
190 "transformer.drop": "cpu",
191 "transformer.h.0": "disk"
192 }
193
194 model = load_checkpoint_and_dispatch(
195 model, checkpoint=weights_location, device_map=device_map
196 )
197
198 ```
199
200 ### Run the model
201
202 Now that we have done this, our model lies across several devices, and maybe the hard drive. But it can still be used as a regular PyTorch model:
203
204 ```py
205 from mingpt.bpe import BPETokenizer
206 tokenizer = BPETokenizer()
207 inputs = tokenizer("Hello, my name is").to(0)
208
209 outputs = model.generate(x1, max_new_tokens=10, do_sample=False)[0]
210 tokenizer.decode(outputs.cpu().squeeze())
211 ```
212
213 Behind the scenes, Accelerate added hooks to the model, so that:
214 - at each layer, the inputs are put on the right device (so even if your model is spread across several GPUs, it works)
215 - for the weights offloaded on the CPU, they are put on a GPU just before the forward pass and cleaned up just after
216 - for the weights offloaded on the hard drive, they are loaded in RAM then put on a GPU just before the forward pass and cleaned up just after
217
218 This way, your model can run for inference even if it doesn't fit on one of the GPUs or the CPU RAM!
219
220 <Tip warning={true}>
221
222 This only supports the inference of your model, not training. Most of the computation happens behind `torch.no_grad()` context managers to avoid spending some GPU memory with intermediate activations.
223
224 </Tip>
225
226 ### Designing a device map
227
228 You can let Accelerate handle the device map computation by setting `device_map` to one of the supported options (`"auto"`, `"balanced"`, `"balanced_low_0"`, `"sequential"`) or create one yourself if you want more control over where each layer should go.
229
230 <Tip>
231
232 You can derive all sizes of the model (and thus compute a `device_map`) on a model that is on the meta device.
233
234 </Tip>
235
236 All the options will produce the same result when you don't have enough GPU memory to accommodate the whole model (which is to fit everything that can on the GPU, then offload weights on the CPU or even on the disk if there is not enough RAM).
237
238 When you have more GPU memory available than the model size, here is the difference between each option:
239 - `"auto"` and `"balanced"` evenly split the model on all available GPUs, making it possible for you to use a batch size greater than 1.
240 - `"balanced_low_0"` evenly splits the model on all GPUs except the first one, and only puts on GPU 0 what does not fit on the others. This option is great when you need to use GPU 0 for some processing of the outputs, like when using the `generate` function for Transformers models
241 - `"sequential"` will fit what it can on GPU 0, then move on GPU 1 and so forth (so won't use the last GPUs if it doesn't need to).
242
243 <Tip>
244
245 The options `"auto"` and `"balanced"` produce the same results for now, but the behavior of `"auto"` might change in the future if we find a strategy that makes more sense, while `"balanced"` will stay stable.
246
247 </Tip>
248
249 First note that you can limit the memory used on each GPU by using the `max_memory` argument (available in [`infer_auto_device_map`] and in all functions using it). When setting `max_memory`, you should pass along a dictionary containing the GPU identifiers (for instance `0`, `1` etc.) and the `"cpu"` key for the maximum RAM you want to use for CPU offload. The values can either be an integer (in bytes) or a string representing a number with its unit, such as `"10GiB"` or `"10GB"`.
250
251 Here is an example where we don't want to use more than 10GiB on each of the two GPUs and no more than 30GiB of CPU RAM for the model weights:
252
253 ```python
254 from accelerate import infer_auto_device_map
255
256 device_map = infer_auto_device_map(my_model, max_memory={0: "10GiB", 1: "10GiB", "cpu": "30GiB"})
257 ```
258
259 <Tip warning={true}>
260
261 When a first allocation happens in PyTorch, it loads CUDA kernels which take about 1-2GB of memory depending on the GPU. Therefore you always have less usable memory than the actual size of the GPU. To see how much memory is actually used do `torch.ones(1).cuda()` and look at the memory usage.
262
263 Therefore when you create memory maps with `max_memory` make sure to adjust the available memory accordingly to avoid out-of-memory errors.
264
265 </Tip>
266
267 Additionally, if you do some additional operations with your outputs without placing them back on the CPU (for instance inside the `generate` method of Transformers) and if you placed your inputs on a GPU, that GPU will consume more memory than the others (Accelerate always place the output back to the device of the input). Therefore if you would like to optimize the maximum batch size and you have many GPUs, give the first GPU less memory. For example, with BLOOM-176B on 8x80 A100 setup, the close-to-ideal map is:
268
269 ```python
270 max_memory = {0: "30GIB", 1: "46GIB", 2: "46GIB", 3: "46GIB", 4: "46GIB", 5: "46GIB", 6: "46GIB", 7: "46GIB"}
271 ```
272 as you can see we gave the remaining 7 GPUs ~50% more memory than GPU 0.
273
274 If you opt to fully design the `device_map` yourself, it should be a dictionary with keys being module names of your model and values being a valid device identifier (for instance an integer for the GPUs) or `"cpu"` for CPU offload, `"disk"` for disk offload. The keys need to cover the whole model, you can then define your device map as you wish: for instance, if your model has two blocks (let's say `block1` and `block2`) which each contain three linear layers (let's say `linear1`, `linear2` and `linear3`), a valid device map can be:
275
276 ```python
277 device_map = {"block1": 0, "block2": 1}
278 ```
279
280 another one that is valid could be:
281
282 ```python
283 device_map = {"block1": 0, "block2.linear1": 0, "block2.linear2": 1, "block2.linear3": 1}
284 ```
285
286 On the other hand, this one is not valid as it does not cover every parameter of the model:
287
288 ```python
289 device_map = {"block1": 0, "block2.linear1": 1, "block2.linear2": 1}
290 ```
291
292 <Tip>
293
294 To be the most efficient, make sure your device map puts the parameters on the GPUs in a sequential manner (e.g. don't put one of the first weights on GPU 0, then weights on GPU 1 and the last weight back to GPU 0) to avoid making many transfers of data between the GPUs.
295
296 </Tip>
297
298 ## CPU offload only
299
300 If you want to offload your model on CPU, you can use [`cpu_offload`]. As a result, all parameters of the model will be offloaded and only one copy of the state dict of the model will be kept. During the forward pass, parameters will be extracted from that state dict and put on the execution device and passed as they are needed, then offloaded again.
301
302 ```python
303 cpu_offload(model, execution_device)
304 ```
305
306 You can also use [`cpu_offload_with_hook`]. This function will offloads a model on the CPU and puts it back to an execution device when executed. The difference with [`cpu_offload`] is that the model stays on the execution device after the forward and is only offloaded again when the `offload` method of the returned `hook` is called. Furthermore, [`cpu_offload_with_hook`] is more performant but less memory saving. It is useful for pipelines running a model in a loop:
307
308 ```python
309 model_1, hook_1 = cpu_offload_with_hook(model_1, execution_device)
310 model_2, hook_2 = cpu_offload_with_hook(model_2, execution_device, prev_module_hook=hook_1)
311 model_3, hook_3 = cpu_offload_with_hook(model_3, execution_device, prev_module_hook=hook_2)
312
313 hid_1 = model_1(input)
314 for i in range(50):
315 # model1 is offloaded on the CPU at the first iteration, model 2 stays on the GPU for this whole loop.
316 hid_2 = model_2(hid_1)
317 # model2 is offloaded to the CPU just before this forward.
318 hid_3 = model_3(hid_3)
319
320 # For model3, you need to manually call the hook offload method.
321 hook_3.offload()
322 ```
323
324 ## Disk offload only
325
326 To perform disk offload, you can use [`disk_offload`]. As a result, all parameters of the model will be offloaded as memory-mapped array in a given folder. During the forward pass, parameters will be accessed from that folder and put on the execution device passed as they are needed, then offloaded again.
327
328 ```python
329 disk_offload(model, offload_dir, execution_device)
330 ```
331
332 ## Limits and further development
333
334 We are aware of the current limitations in the API:
335
336 - [`infer_auto_device_map`] (or `device_map="auto"` in [`load_checkpoint_and_dispatch`]) tries to maximize GPU and CPU RAM it sees available when you execute it. While PyTorch is very good at managing GPU RAM efficiently (and giving it back when not needed), it's not entirely true with Python and CPU RAM. Therefore, an automatically computed device map might be too intense on the CPU. Move a few modules to the disk device if you get crashes due to a lack of RAM.
337 - [`infer_auto_device_map`] (or `device_map="auto"` in [`load_checkpoint_and_dispatch`]) attributes devices sequentially (to avoid moving things back and forth) so if your first layer is bigger than the size of the GPU you have, it will end up with everything on the CPU/Disk.
338 - [`load_checkpoint_and_dispatch`] and [`load_checkpoint_in_model`] do not perform any check on the correctness of your state dict compared to your model at the moment (this will be fixed in a future version), so you may get some weird errors if trying to load a checkpoint with mismatched or missing keys.
339 - The model parallelism used when your model is split on several GPUs is naive and not optimized, meaning that only one GPU works at a given time and the other sits idle.
340 - When weights are offloaded on the CPU/hard drive, there is no pre-fetching (yet, we will work on this for future versions) which means the weights are put on the GPU when they are needed and not before.
341 - Hard-drive offloading might be very slow if the hardware you run on does not have fast communication between disk and CPU (like NVMes).