Debian Codegraph @

docs/source/usage_guides/big_modeling.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 # Big Model Inference
17
18 One of the biggest advancements Accelerate provides is [Big Model Inference](../concept_guides/big_model_inference), which allows you to perform inference with models that don't fully fit on your graphics card.
19
20 This tutorial will show you how to use Big Model Inference in Accelerate and the Hugging Face ecosystem.
21
22 ## Accelerate
23
24 A typical workflow for loading a PyTorch model is shown below. `ModelClass` is a model that exceeds the GPU memory of your device (mps or cuda or xpu).
25
26 ```py
27 import torch
28
29 my_model = ModelClass(...)
30 state_dict = torch.load(checkpoint_file)
31 my_model.load_state_dict(state_dict)
32 ```
33
34 With Big Model Inference, the first step is to init an empty skeleton of the model with the `init_empty_weights` context manager. This doesn't require any memory because `my_model` is "parameterless".
35
36 ```py
37 from accelerate import init_empty_weights
38 with init_empty_weights():
39 my_model = ModelClass(...)
40 ```
41
42 Next, the weights are loaded into the model for inference.
43
44 The [`load_checkpoint_and_dispatch`] method loads a checkpoint inside your empty model and dispatches the weights for each layer across all available devices, starting with the fastest devices (GPU, MPS, XPU, NPU, MLU, SDAA, MUSA) first before moving to the slower ones (CPU and hard drive).
45
46 Setting `device_map="auto"` automatically fills all available space on the GPU(s) first, then the CPU, and finally, the hard drive (the absolute slowest option) if there is still not enough memory.
47
48 > [!TIP]
49 > Refer to the [Designing a device map](../concept_guides/big_model_inference#designing-a-device-map) guide for more details on how to design your own device map.
50
51 ```py
52 from accelerate import load_checkpoint_and_dispatch
53
54 model = load_checkpoint_and_dispatch(
55 model, checkpoint=checkpoint_file, device_map="auto"
56 )
57 ```
58
59 If there are certain “chunks” of layers that shouldn’t be split, pass them to `no_split_module_classes` (see [here](../concept_guides/big_model_inference#loading-weights) for more details).
60
61 A models weights can also be sharded into multiple checkpoints to save memory, such as when the `state_dict` doesn't fit in memory (see [here](../concept_guides/big_model_inference#sharded-checkpoints) for more details).
62
63 Now that the model is fully dispatched, you can perform inference.
64
65 ```py
66 input = torch.randn(2,3)
67 device_type = next(iter(model.parameters())).device.type
68 input = input.to(device_type)
69 output = model(input)
70 ```
71
72 Each time an input is passed through a layer, it is sent from the CPU to the GPU (or disk to CPU to GPU), the output is calculated, and the layer is removed from the GPU going back down the line. While this adds some overhead to inference, it enables you to run any size model on your system, as long as the largest layer fits on your GPU.
73
74 Multiple GPUs, or "model parallelism", can be utilized but only one GPU will be active at any given moment. This forces the GPU to wait for the previous GPU to send it the output. You should launch your script normally with Python instead of other tools like torchrun and accelerate launch.
75
76 > [!TIP]
77 > You may also be interested in *pipeline parallelism* which utilizes all available GPUs at once, instead of only having one GPU active at a time. This approach is less flexible though. For more details, refer to the [Memory-efficient pipeline parallelism](./distributed_inference#memory-efficient-pipeline-parallelism-experimental) guide.
78
79 <Youtube id="MWCSGj9jEAo"/>
80
81 Take a look at a full example of Big Model Inference below.
82
83 ```py
84 import torch
85 from accelerate import init_empty_weights, load_checkpoint_and_dispatch
86
87 with init_empty_weights():
88 model = MyModel(...)
89
90 model = load_checkpoint_and_dispatch(
91 model, checkpoint=checkpoint_file, device_map="auto"
92 )
93
94 input = torch.randn(2,3)
95 device_type = next(iter(model.parameters())).device.type
96 input = input.to(device_type)
97 output = model(input)
98 ```
99
100 ## Hugging Face ecosystem
101
102 Other libraries in the Hugging Face ecosystem, like Transformers or Diffusers, supports Big Model Inference in their [`~transformers.PreTrainedModel.from_pretrained`] constructors.
103
104 You just need to add `device_map="auto"` in [`~transformers.PreTrainedModel.from_pretrained`] to enable Big Model Inference.
105
106 For example, load Big Sciences T0pp 11 billion parameter model with Big Model Inference.
107
108 ```py
109 from transformers import AutoModelForSeq2SeqLM
110
111 model = AutoModelForSeq2SeqLM.from_pretrained("bigscience/T0pp", device_map="auto")
112 ```
113
114 After loading the model, the empty init and smart dispatch steps from before are executed and the model is fully ready to make use of all the resources in your machine. Through these constructors, you can also save more memory by specifying the `torch_dtype` parameter to load a model in a lower precision.
115
116 ```py
117 from transformers import AutoModelForSeq2SeqLM
118
119 model = AutoModelForSeq2SeqLM.from_pretrained("bigscience/T0pp", device_map="auto", torch_dtype=torch.float16)
120 ```
121
122 ## Next steps
123
124 For a more detailed explanation of Big Model Inference, make sure to check out the [conceptual guide](../concept_guides/big_model_inference)!