| 1 |
<!--Copyright 2023 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 |
# Distributed inference |
| 17 |
|
| 18 |
Distributed inference can fall into three brackets: |
| 19 |
|
| 20 |
1. Loading an entire model onto each GPU and sending chunks of a batch through each GPU's model copy at a time |
| 21 |
2. Loading parts of a model onto each GPU and processing a single input at one time |
| 22 |
3. Loading parts of a model onto each GPU and using what is called scheduled Pipeline Parallelism to combine the two prior techniques. |
| 23 |
|
| 24 |
We're going to go through the first and the last bracket, showcasing how to do each as they are more realistic scenarios. |
| 25 |
|
| 26 |
|
| 27 |
## Sending chunks of a batch automatically to each loaded model |
| 28 |
|
| 29 |
This is the most memory-intensive solution, as it requires each GPU to keep a full copy of the model in memory at a given time. |
| 30 |
|
| 31 |
Normally when doing this, users send the model to a specific device to load it from the CPU, and then move each prompt to a different device. |
| 32 |
|
| 33 |
A basic pipeline using the `diffusers` library might look something like so: |
| 34 |
|
| 35 |
```python |
| 36 |
import torch |
| 37 |
import torch.distributed as dist |
| 38 |
from diffusers import DiffusionPipeline |
| 39 |
|
| 40 |
pipe = DiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16) |
| 41 |
``` |
| 42 |
Followed then by performing inference based on the specific prompt: |
| 43 |
|
| 44 |
```python |
| 45 |
def run_inference(rank, world_size): |
| 46 |
dist.init_process_group("nccl", rank=rank, world_size=world_size) |
| 47 |
pipe.to(rank) |
| 48 |
|
| 49 |
if torch.distributed.get_rank() == 0: |
| 50 |
prompt = "a dog" |
| 51 |
elif torch.distributed.get_rank() == 1: |
| 52 |
prompt = "a cat" |
| 53 |
|
| 54 |
result = pipe(prompt).images[0] |
| 55 |
result.save(f"result_{rank}.png") |
| 56 |
``` |
| 57 |
One will notice how we have to check the rank to know what prompt to send, which can be a bit tedious. |
| 58 |
|
| 59 |
A user might then also think that with Accelerate, using the `Accelerator` to prepare a dataloader for such a task might also be |
| 60 |
a simple way to manage this. (To learn more, check out the relevant section in the [Quick Tour](../quicktour#distributed-evaluation)) |
| 61 |
|
| 62 |
Can it manage it? Yes. Does it add unneeded extra code however: also yes. |
| 63 |
|
| 64 |
|
| 65 |
With Accelerate, we can simplify this process by using the [`Accelerator.split_between_processes`] context manager (which also exists in `PartialState` and `AcceleratorState`). |
| 66 |
This function will automatically split whatever data you pass to it (be it a prompt, a set of tensors, a dictionary of the prior data, etc.) across all the processes (with a potential |
| 67 |
to be padded) for you to use right away. |
| 68 |
|
| 69 |
Let's rewrite the above example using this context manager: |
| 70 |
|
| 71 |
```python |
| 72 |
import torch |
| 73 |
from accelerate import PartialState # Can also be Accelerator or AcceleratorState |
| 74 |
from diffusers import DiffusionPipeline |
| 75 |
|
| 76 |
pipe = DiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16) |
| 77 |
distributed_state = PartialState() |
| 78 |
pipe.to(distributed_state.device) |
| 79 |
|
| 80 |
# Assume two processes |
| 81 |
with distributed_state.split_between_processes(["a dog", "a cat"]) as prompt: |
| 82 |
result = pipe(prompt).images[0] |
| 83 |
result.save(f"result_{distributed_state.process_index}.png") |
| 84 |
``` |
| 85 |
|
| 86 |
And then to launch the code, we can use the Accelerate: |
| 87 |
|
| 88 |
If you have generated a config file to be used using `accelerate config`: |
| 89 |
|
| 90 |
```bash |
| 91 |
accelerate launch distributed_inference.py |
| 92 |
``` |
| 93 |
|
| 94 |
If you have a specific config file you want to use: |
| 95 |
|
| 96 |
```bash |
| 97 |
accelerate launch --config_file my_config.json distributed_inference.py |
| 98 |
``` |
| 99 |
|
| 100 |
Or if don't want to make any config files and launch on two GPUs: |
| 101 |
|
| 102 |
> Note: You will get some warnings about values being guessed based on your system. To remove these you can do `accelerate config default` or go through `accelerate config` to create a config file. |
| 103 |
|
| 104 |
```bash |
| 105 |
accelerate launch --num_processes 2 distributed_inference.py |
| 106 |
``` |
| 107 |
|
| 108 |
We've now reduced the boilerplate code needed to split this data to a few lines of code quite easily. |
| 109 |
|
| 110 |
But what if we have an odd distribution of prompts to GPUs? For example, what if we have 3 prompts, but only 2 GPUs? |
| 111 |
|
| 112 |
Under the context manager, the first GPU would receive the first two prompts and the second GPU the third, ensuring that |
| 113 |
all prompts are split and no overhead is needed. |
| 114 |
|
| 115 |
*However*, what if we then wanted to do something with the results of *all the GPUs*? (Say gather them all and perform some kind of post processing) |
| 116 |
You can pass in `apply_padding=True` to ensure that the lists of prompts are padded to the same length, with extra data being taken |
| 117 |
from the last sample. This way all GPUs will have the same number of prompts, and you can then gather the results. |
| 118 |
|
| 119 |
<Tip> |
| 120 |
|
| 121 |
This is only needed when trying to perform an action such as gathering the results, where the data on each device |
| 122 |
needs to be the same length. Basic inference does not require this. |
| 123 |
|
| 124 |
</Tip> |
| 125 |
|
| 126 |
For instance: |
| 127 |
|
| 128 |
```python |
| 129 |
import torch |
| 130 |
from accelerate import PartialState # Can also be Accelerator or AcceleratorState |
| 131 |
from diffusers import DiffusionPipeline |
| 132 |
|
| 133 |
pipe = DiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16) |
| 134 |
distributed_state = PartialState() |
| 135 |
pipe.to(distributed_state.device) |
| 136 |
|
| 137 |
# Assume two processes |
| 138 |
with distributed_state.split_between_processes(["a dog", "a cat", "a chicken"], apply_padding=True) as prompt: |
| 139 |
result = pipe(prompt).images |
| 140 |
``` |
| 141 |
|
| 142 |
On the first GPU, the prompts will be `["a dog", "a cat"]`, and on the second GPU it will be `["a chicken", "a chicken"]`. |
| 143 |
Make sure to drop the final sample, as it will be a duplicate of the previous one. |
| 144 |
|
| 145 |
You can find more complex examples [here](https://github.com/huggingface/accelerate/tree/main/examples/inference/distributed) such as how to use it with LLMs. |
| 146 |
|
| 147 |
## Memory-efficient pipeline parallelism (experimental) |
| 148 |
|
| 149 |
This next part will discuss using *pipeline parallelism*. This is an **experimental** API that utilizes [torch.distributed.pipelining](https://pytorch.org/docs/stable/distributed.pipelining.html#) as a native solution. |
| 150 |
|
| 151 |
The general idea with pipeline parallelism is: say you have 4 GPUs and a model big enough it can be *split* on four GPUs using `device_map="auto"`. With this method you can send in 4 inputs at a time (for example here, any amount works) and each model chunk will work on an input, then receive the next input once the prior chunk finished, making it *much* more efficient **and faster** than the method described earlier. Here's a visual taken from the PyTorch repository: |
| 152 |
|
| 153 |
 |
| 154 |
|
| 155 |
To illustrate how you can use this with Accelerate, we have created an [example zoo](https://github.com/huggingface/accelerate/tree/main/examples/inference) showcasing a number of different models and situations. In this tutorial, we'll show this method for GPT2 across two GPUs. |
| 156 |
|
| 157 |
Before you proceed, please make sure you have the latest PyTorch version installed by running the following: |
| 158 |
|
| 159 |
```bash |
| 160 |
pip install torch |
| 161 |
``` |
| 162 |
|
| 163 |
Start by creating the model on the CPU: |
| 164 |
|
| 165 |
```{python} |
| 166 |
from transformers import GPT2ForSequenceClassification, GPT2Config |
| 167 |
|
| 168 |
config = GPT2Config() |
| 169 |
model = GPT2ForSequenceClassification(config) |
| 170 |
model.eval() |
| 171 |
``` |
| 172 |
|
| 173 |
Next you'll need to create some example inputs to use. These help `torch.distributed.pipelining` trace the model. |
| 174 |
|
| 175 |
<Tip warning={true}> |
| 176 |
However you make this example will determine the relative batch size that will be used/passed |
| 177 |
through the model at a given time, so make sure to remember how many items there are! |
| 178 |
</Tip> |
| 179 |
|
| 180 |
```{python} |
| 181 |
input = torch.randint( |
| 182 |
low=0, |
| 183 |
high=config.vocab_size, |
| 184 |
size=(2, 1024), # bs x seq_len |
| 185 |
device="cpu", |
| 186 |
dtype=torch.int64, |
| 187 |
requires_grad=False, |
| 188 |
) |
| 189 |
``` |
| 190 |
Next we need to actually perform the tracing and get the model ready. To do so, use the [`inference.prepare_pippy`] function and it will fully wrap the model for pipeline parallelism automatically: |
| 191 |
|
| 192 |
```{python} |
| 193 |
from accelerate.inference import prepare_pippy |
| 194 |
example_inputs = {"input_ids": input} |
| 195 |
model = prepare_pippy(model, example_args=(input,)) |
| 196 |
``` |
| 197 |
|
| 198 |
<Tip> |
| 199 |
|
| 200 |
There are a variety of parameters you can pass through to `prepare_pippy`: |
| 201 |
|
| 202 |
* `split_points` lets you determine what layers to split the model at. By default we use wherever `device_map="auto" declares, such as `fc` or `conv1`. |
| 203 |
|
| 204 |
* `num_chunks` determines how the batch will be split and sent to the model itself (so `num_chunks=1` with four split points/four GPUs will have a naive MP where a single input gets passed between the four layer split points) |
| 205 |
|
| 206 |
</Tip> |
| 207 |
|
| 208 |
From here, all that's left is to actually perform the distributed inference! |
| 209 |
|
| 210 |
<Tip warning={true}> |
| 211 |
|
| 212 |
When passing inputs, we highly recommend to pass them in as a tuple of arguments. Using `kwargs` is supported, however, this approach is experimental. |
| 213 |
</Tip> |
| 214 |
|
| 215 |
```{python} |
| 216 |
args = some_more_arguments |
| 217 |
with torch.no_grad(): |
| 218 |
output = model(*args) |
| 219 |
``` |
| 220 |
|
| 221 |
When finished all the data will be on the last process only: |
| 222 |
|
| 223 |
```{python} |
| 224 |
from accelerate import PartialState |
| 225 |
if PartialState().is_last_process: |
| 226 |
print(output) |
| 227 |
``` |
| 228 |
|
| 229 |
<Tip> |
| 230 |
|
| 231 |
If you pass in `gather_output=True` to [`inference.prepare_pippy`], the output will be sent |
| 232 |
across to all the GPUs afterwards without needing the `is_last_process` check. This is |
| 233 |
`False` by default as it incurs a communication call. |
| 234 |
|
| 235 |
</Tip> |
| 236 |
|
| 237 |
And that's it! To explore more, please check out the inference examples in the [Accelerate repo](https://github.com/huggingface/accelerate/tree/main/examples/inference/pippy) and our [documentation](../package_reference/inference) as we work to improving this integration. |