| 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 |
# Launching distributed training from Jupyter Notebooks |
| 17 |
|
| 18 |
This tutorial teaches you how to fine-tune a computer vision model with 🤗 Accelerate from a Jupyter Notebook on a distributed system. |
| 19 |
You will also learn how to set up a few requirements needed for ensuring your environment is configured properly, your data has been prepared properly, and finally how to launch training. |
| 20 |
|
| 21 |
<Tip> |
| 22 |
|
| 23 |
This tutorial is also available as a Jupyter Notebook [here](https://github.com/huggingface/notebooks/blob/main/examples/accelerate_examples/simple_cv_example.ipynb) |
| 24 |
|
| 25 |
</Tip> |
| 26 |
|
| 27 |
## Configuring the Environment |
| 28 |
|
| 29 |
Before any training can be performed, an Accelerate config file must exist in the system. Usually this can be done by running the following in a terminal and answering the prompts: |
| 30 |
|
| 31 |
```bash |
| 32 |
accelerate config |
| 33 |
``` |
| 34 |
|
| 35 |
However, if general defaults are fine and you are *not* running on a TPU, Accelerate has a utility to quickly write your device configuration into a config file via [`utils.write_basic_config`]. |
| 36 |
|
| 37 |
The following code will restart Jupyter after writing the configuration, as CUDA runtime or XPU runtime was called to perform this. |
| 38 |
|
| 39 |
<Tip warning={true}> |
| 40 |
|
| 41 |
CUDA and XPU can't be initialized more than once on a multi-device system. It's fine to debug in the notebook and have calls to CUDA/XPU, but in order to finally train a full cleanup and restart will need to be performed. |
| 42 |
|
| 43 |
</Tip> |
| 44 |
|
| 45 |
```python |
| 46 |
import os |
| 47 |
from accelerate.utils import write_basic_config |
| 48 |
|
| 49 |
write_basic_config() # Write a config file |
| 50 |
os._exit(00) # Restart the notebook |
| 51 |
``` |
| 52 |
|
| 53 |
## Preparing the Dataset and Model |
| 54 |
|
| 55 |
Next you should prepare your dataset. As mentioned earlier, great care should be taken when preparing the `DataLoaders` and model to make sure that **nothing** is put on *any* GPU. |
| 56 |
|
| 57 |
If you do, it is recommended to put that specific code into a function and call that from within the notebook launcher interface, which will be shown later. |
| 58 |
|
| 59 |
Make sure the dataset is downloaded based on the directions [here](https://github.com/huggingface/accelerate/tree/main/examples#simple-vision-example) |
| 60 |
|
| 61 |
```python |
| 62 |
import os, re, torch, PIL |
| 63 |
import numpy as np |
| 64 |
|
| 65 |
from torch.optim.lr_scheduler import OneCycleLR |
| 66 |
from torch.utils.data import DataLoader, Dataset |
| 67 |
from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor |
| 68 |
|
| 69 |
from accelerate import Accelerator |
| 70 |
from accelerate.utils import set_seed |
| 71 |
from timm import create_model |
| 72 |
``` |
| 73 |
|
| 74 |
First you need to create a function to extract the class name based on a filename: |
| 75 |
|
| 76 |
```python |
| 77 |
import os |
| 78 |
|
| 79 |
data_dir = "../../images" |
| 80 |
fnames = os.listdir(data_dir) |
| 81 |
fname = fnames[0] |
| 82 |
print(fname) |
| 83 |
``` |
| 84 |
|
| 85 |
```python out |
| 86 |
beagle_32.jpg |
| 87 |
``` |
| 88 |
|
| 89 |
In the case here, the label is `beagle`. Using regex you can extract the label from the filename: |
| 90 |
|
| 91 |
```python |
| 92 |
import re |
| 93 |
|
| 94 |
|
| 95 |
def extract_label(fname): |
| 96 |
stem = fname.split(os.path.sep)[-1] |
| 97 |
return re.search(r"^(.*)_\d+\.jpg$", stem).groups()[0] |
| 98 |
``` |
| 99 |
|
| 100 |
```python |
| 101 |
extract_label(fname) |
| 102 |
``` |
| 103 |
|
| 104 |
And you can see it properly returned the right name for our file: |
| 105 |
|
| 106 |
```python out |
| 107 |
"beagle" |
| 108 |
``` |
| 109 |
|
| 110 |
Next a `Dataset` class should be made to handle grabbing the image and the label: |
| 111 |
|
| 112 |
```python |
| 113 |
class PetsDataset(Dataset): |
| 114 |
def __init__(self, file_names, image_transform=None, label_to_id=None): |
| 115 |
self.file_names = file_names |
| 116 |
self.image_transform = image_transform |
| 117 |
self.label_to_id = label_to_id |
| 118 |
|
| 119 |
def __len__(self): |
| 120 |
return len(self.file_names) |
| 121 |
|
| 122 |
def __getitem__(self, idx): |
| 123 |
fname = self.file_names[idx] |
| 124 |
raw_image = PIL.Image.open(fname) |
| 125 |
image = raw_image.convert("RGB") |
| 126 |
if self.image_transform is not None: |
| 127 |
image = self.image_transform(image) |
| 128 |
label = extract_label(fname) |
| 129 |
if self.label_to_id is not None: |
| 130 |
label = self.label_to_id[label] |
| 131 |
return {"image": image, "label": label} |
| 132 |
``` |
| 133 |
|
| 134 |
Now to build the dataset. Outside the training function you can find and declare all the filenames and labels and use them as references inside the |
| 135 |
launched function: |
| 136 |
|
| 137 |
```python |
| 138 |
fnames = [os.path.join("../../images", fname) for fname in fnames if fname.endswith(".jpg")] |
| 139 |
``` |
| 140 |
|
| 141 |
Next gather all the labels: |
| 142 |
|
| 143 |
```python |
| 144 |
all_labels = [extract_label(fname) for fname in fnames] |
| 145 |
id_to_label = list(set(all_labels)) |
| 146 |
id_to_label.sort() |
| 147 |
label_to_id = {lbl: i for i, lbl in enumerate(id_to_label)} |
| 148 |
``` |
| 149 |
|
| 150 |
Next, you should make a `get_dataloaders` function that will return your built dataloaders for you. As mentioned earlier, if data is automatically |
| 151 |
sent to the GPU or a TPU device when building your `DataLoaders`, they must be built using this method. |
| 152 |
|
| 153 |
```python |
| 154 |
def get_dataloaders(batch_size: int = 64): |
| 155 |
"Builds a set of dataloaders with a batch_size" |
| 156 |
random_perm = np.random.permutation(len(fnames)) |
| 157 |
cut = int(0.8 * len(fnames)) |
| 158 |
train_split = random_perm[:cut] |
| 159 |
eval_split = random_perm[cut:] |
| 160 |
|
| 161 |
# For training a simple RandomResizedCrop will be used |
| 162 |
train_tfm = Compose([RandomResizedCrop((224, 224), scale=(0.5, 1.0)), ToTensor()]) |
| 163 |
train_dataset = PetsDataset([fnames[i] for i in train_split], image_transform=train_tfm, label_to_id=label_to_id) |
| 164 |
|
| 165 |
# For evaluation a deterministic Resize will be used |
| 166 |
eval_tfm = Compose([Resize((224, 224)), ToTensor()]) |
| 167 |
eval_dataset = PetsDataset([fnames[i] for i in eval_split], image_transform=eval_tfm, label_to_id=label_to_id) |
| 168 |
|
| 169 |
# Instantiate dataloaders |
| 170 |
train_dataloader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size, num_workers=4) |
| 171 |
eval_dataloader = DataLoader(eval_dataset, shuffle=False, batch_size=batch_size * 2, num_workers=4) |
| 172 |
return train_dataloader, eval_dataloader |
| 173 |
``` |
| 174 |
|
| 175 |
Finally, you should import the scheduler to be used later: |
| 176 |
|
| 177 |
```python |
| 178 |
from torch.optim.lr_scheduler import CosineAnnealingLR |
| 179 |
``` |
| 180 |
|
| 181 |
## Writing the Training Function |
| 182 |
|
| 183 |
Now you can build the training loop. [`notebook_launcher`] works by passing in a function to call that will be ran across the distributed system. |
| 184 |
|
| 185 |
Here is a basic training loop for the animal classification problem: |
| 186 |
|
| 187 |
<Tip> |
| 188 |
|
| 189 |
The code has been split up to allow for explanations on each section. A full version that can be copy and pasted will be available at the end |
| 190 |
|
| 191 |
</Tip> |
| 192 |
|
| 193 |
|
| 194 |
```python |
| 195 |
def training_loop(mixed_precision="fp16", seed: int = 42, batch_size: int = 64): |
| 196 |
set_seed(seed) |
| 197 |
accelerator = Accelerator(mixed_precision=mixed_precision) |
| 198 |
``` |
| 199 |
|
| 200 |
First you should set the seed and create an [`Accelerator`] object as early in the training loop as possible. |
| 201 |
|
| 202 |
<Tip warning={true}> |
| 203 |
|
| 204 |
If training on the TPU, your training loop should take in the model as a parameter and it should be instantiated |
| 205 |
outside of the training loop function. See the [TPU best practices](../concept_guides/training_tpu) |
| 206 |
to learn why |
| 207 |
|
| 208 |
</Tip> |
| 209 |
|
| 210 |
Next you should build your dataloaders and create your model: |
| 211 |
|
| 212 |
```python |
| 213 |
train_dataloader, eval_dataloader = get_dataloaders(batch_size) |
| 214 |
model = create_model("resnet50d", pretrained=True, num_classes=len(label_to_id)) |
| 215 |
``` |
| 216 |
|
| 217 |
<Tip> |
| 218 |
|
| 219 |
You build the model here so that the seed also controls the new weight initialization |
| 220 |
|
| 221 |
</Tip> |
| 222 |
|
| 223 |
As you are performing transfer learning in this example, the encoder of the model starts out frozen so the head of the model can be |
| 224 |
trained only initially: |
| 225 |
|
| 226 |
```python |
| 227 |
for param in model.parameters(): |
| 228 |
param.requires_grad = False |
| 229 |
for param in model.get_classifier().parameters(): |
| 230 |
param.requires_grad = True |
| 231 |
``` |
| 232 |
|
| 233 |
Normalizing the batches of images will make training a little faster: |
| 234 |
|
| 235 |
```python |
| 236 |
mean = torch.tensor(model.default_cfg["mean"])[None, :, None, None] |
| 237 |
std = torch.tensor(model.default_cfg["std"])[None, :, None, None] |
| 238 |
``` |
| 239 |
|
| 240 |
To make these constants available on the active device, you should set it to the Accelerator's device: |
| 241 |
|
| 242 |
```python |
| 243 |
mean = mean.to(accelerator.device) |
| 244 |
std = std.to(accelerator.device) |
| 245 |
``` |
| 246 |
|
| 247 |
Next instantiate the rest of the PyTorch classes used for training: |
| 248 |
|
| 249 |
```python |
| 250 |
optimizer = torch.optim.Adam(params=model.parameters(), lr=3e-2 / 25) |
| 251 |
lr_scheduler = OneCycleLR(optimizer=optimizer, max_lr=3e-2, epochs=5, steps_per_epoch=len(train_dataloader)) |
| 252 |
``` |
| 253 |
|
| 254 |
Before passing everything to [`~Accelerator.prepare`]. |
| 255 |
|
| 256 |
<Tip> |
| 257 |
|
| 258 |
There is no specific order to remember, you just need to unpack the objects in the same order you gave them to the prepare method. |
| 259 |
|
| 260 |
</Tip> |
| 261 |
|
| 262 |
```python |
| 263 |
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( |
| 264 |
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler |
| 265 |
) |
| 266 |
``` |
| 267 |
|
| 268 |
Now train the model: |
| 269 |
|
| 270 |
```python |
| 271 |
for epoch in range(5): |
| 272 |
model.train() |
| 273 |
for batch in train_dataloader: |
| 274 |
inputs = (batch["image"] - mean) / std |
| 275 |
outputs = model(inputs) |
| 276 |
loss = torch.nn.functional.cross_entropy(outputs, batch["label"]) |
| 277 |
accelerator.backward(loss) |
| 278 |
optimizer.step() |
| 279 |
lr_scheduler.step() |
| 280 |
optimizer.zero_grad() |
| 281 |
``` |
| 282 |
|
| 283 |
The evaluation loop will look slightly different compared to the training loop. The number of elements passed as well as the overall |
| 284 |
total accuracy of each batch will be added to two constants: |
| 285 |
|
| 286 |
```python |
| 287 |
model.eval() |
| 288 |
accurate = 0 |
| 289 |
num_elems = 0 |
| 290 |
``` |
| 291 |
|
| 292 |
Next you have the rest of your standard PyTorch loop: |
| 293 |
|
| 294 |
```python |
| 295 |
for batch in eval_dataloader: |
| 296 |
inputs = (batch["image"] - mean) / std |
| 297 |
with torch.no_grad(): |
| 298 |
outputs = model(inputs) |
| 299 |
predictions = outputs.argmax(dim=-1) |
| 300 |
``` |
| 301 |
|
| 302 |
Before finally the last major difference. |
| 303 |
|
| 304 |
When performing distributed evaluation, the predictions and labels need to be passed through |
| 305 |
[`~Accelerator.gather`] so that all of the data is available on the current device and a properly calculated metric can be achieved: |
| 306 |
|
| 307 |
```python |
| 308 |
accurate_preds = accelerator.gather(predictions) == accelerator.gather(batch["label"]) |
| 309 |
num_elems += accurate_preds.shape[0] |
| 310 |
accurate += accurate_preds.long().sum() |
| 311 |
``` |
| 312 |
|
| 313 |
Now you just need to calculate the actual metric for this problem, and you can print it on the main process using [`~Accelerator.print`]: |
| 314 |
|
| 315 |
```python |
| 316 |
eval_metric = accurate.item() / num_elems |
| 317 |
accelerator.print(f"epoch {epoch}: {100 * eval_metric:.2f}") |
| 318 |
``` |
| 319 |
|
| 320 |
A full version of this training loop is available below: |
| 321 |
|
| 322 |
```python |
| 323 |
def training_loop(mixed_precision="fp16", seed: int = 42, batch_size: int = 64): |
| 324 |
set_seed(seed) |
| 325 |
# Initialize accelerator |
| 326 |
accelerator = Accelerator(mixed_precision=mixed_precision) |
| 327 |
# Build dataloaders |
| 328 |
train_dataloader, eval_dataloader = get_dataloaders(batch_size) |
| 329 |
|
| 330 |
# Instantiate the model (you build the model here so that the seed also controls new weight initializations) |
| 331 |
model = create_model("resnet50d", pretrained=True, num_classes=len(label_to_id)) |
| 332 |
|
| 333 |
# Freeze the base model |
| 334 |
for param in model.parameters(): |
| 335 |
param.requires_grad = False |
| 336 |
for param in model.get_classifier().parameters(): |
| 337 |
param.requires_grad = True |
| 338 |
|
| 339 |
# You can normalize the batches of images to be a bit faster |
| 340 |
mean = torch.tensor(model.default_cfg["mean"])[None, :, None, None] |
| 341 |
std = torch.tensor(model.default_cfg["std"])[None, :, None, None] |
| 342 |
|
| 343 |
# To make these constants available on the active device, set it to the accelerator device |
| 344 |
mean = mean.to(accelerator.device) |
| 345 |
std = std.to(accelerator.device) |
| 346 |
|
| 347 |
# Instantiate the optimizer |
| 348 |
optimizer = torch.optim.Adam(params=model.parameters(), lr=3e-2 / 25) |
| 349 |
|
| 350 |
# Instantiate the learning rate scheduler |
| 351 |
lr_scheduler = OneCycleLR(optimizer=optimizer, max_lr=3e-2, epochs=5, steps_per_epoch=len(train_dataloader)) |
| 352 |
|
| 353 |
# Prepare everything |
| 354 |
# There is no specific order to remember, you just need to unpack the objects in the same order you gave them to the |
| 355 |
# prepare method. |
| 356 |
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( |
| 357 |
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler |
| 358 |
) |
| 359 |
|
| 360 |
# Now you train the model |
| 361 |
for epoch in range(5): |
| 362 |
model.train() |
| 363 |
for batch in train_dataloader: |
| 364 |
inputs = (batch["image"] - mean) / std |
| 365 |
outputs = model(inputs) |
| 366 |
loss = torch.nn.functional.cross_entropy(outputs, batch["label"]) |
| 367 |
accelerator.backward(loss) |
| 368 |
optimizer.step() |
| 369 |
lr_scheduler.step() |
| 370 |
optimizer.zero_grad() |
| 371 |
|
| 372 |
model.eval() |
| 373 |
accurate = 0 |
| 374 |
num_elems = 0 |
| 375 |
for batch in eval_dataloader: |
| 376 |
inputs = (batch["image"] - mean) / std |
| 377 |
with torch.no_grad(): |
| 378 |
outputs = model(inputs) |
| 379 |
predictions = outputs.argmax(dim=-1) |
| 380 |
accurate_preds = accelerator.gather(predictions) == accelerator.gather(batch["label"]) |
| 381 |
num_elems += accurate_preds.shape[0] |
| 382 |
accurate += accurate_preds.long().sum() |
| 383 |
|
| 384 |
eval_metric = accurate.item() / num_elems |
| 385 |
# Use accelerator.print to print only on the main process. |
| 386 |
accelerator.print(f"epoch {epoch}: {100 * eval_metric:.2f}") |
| 387 |
``` |
| 388 |
|
| 389 |
## Using the notebook_launcher |
| 390 |
|
| 391 |
All that's left is to use the [`notebook_launcher`]. |
| 392 |
|
| 393 |
You pass in the function, the arguments (as a tuple), and the number of processes to train on. (See the [documentation](../package_reference/launchers) for more information) |
| 394 |
|
| 395 |
```python |
| 396 |
from accelerate import notebook_launcher |
| 397 |
``` |
| 398 |
|
| 399 |
```python |
| 400 |
args = ("fp16", 42, 64) |
| 401 |
notebook_launcher(training_loop, args, num_processes=2) |
| 402 |
``` |
| 403 |
|
| 404 |
In the case of running on multiple nodes, you need to set up a Jupyter session at each node and run the launching cell at the same time. |
| 405 |
|
| 406 |
For an environment containing 2 nodes (computers) with 8 GPUs each and the main computer with an IP address of "172.31.43.8", it would look like so: |
| 407 |
|
| 408 |
```python |
| 409 |
notebook_launcher(training_loop, args, master_addr="172.31.43.8", node_rank=0, num_nodes=2, num_processes=8) |
| 410 |
``` |
| 411 |
|
| 412 |
And in the second Jupyter session on the other machine: |
| 413 |
|
| 414 |
<Tip> |
| 415 |
|
| 416 |
Notice how the `node_rank` has changed |
| 417 |
|
| 418 |
</Tip> |
| 419 |
|
| 420 |
```python |
| 421 |
notebook_launcher(training_loop, args, master_addr="172.31.43.8", node_rank=1, num_nodes=2, num_processes=8) |
| 422 |
``` |
| 423 |
|
| 424 |
In the case of running on the TPU, it would look like so: |
| 425 |
|
| 426 |
```python |
| 427 |
model = create_model("resnet50d", pretrained=True, num_classes=len(label_to_id)) |
| 428 |
|
| 429 |
args = (model, "fp16", 42, 64) |
| 430 |
notebook_launcher(training_loop, args, num_processes=8) |
| 431 |
``` |
| 432 |
|
| 433 |
To launch the training process with elasticity, enabling fault tolerance, you can use the `elastic_launch` feature provided by PyTorch. This requires setting additional parameters such as `rdzv_backend` and `max_restarts`. Here is an example of how to use `notebook_launcher` with elastic capabilities: |
| 434 |
|
| 435 |
```python |
| 436 |
notebook_launcher( |
| 437 |
training_loop, |
| 438 |
args, |
| 439 |
num_processes=2, |
| 440 |
max_restarts=3 |
| 441 |
) |
| 442 |
``` |
| 443 |
|
| 444 |
As it's running it will print the progress as well as state how many devices you ran on. This tutorial was ran with two GPUs: |
| 445 |
|
| 446 |
```python out |
| 447 |
Launching training on 2 GPUs. |
| 448 |
epoch 0: 88.12 |
| 449 |
epoch 1: 91.73 |
| 450 |
epoch 2: 92.58 |
| 451 |
epoch 3: 93.90 |
| 452 |
epoch 4: 94.71 |
| 453 |
``` |
| 454 |
|
| 455 |
And that's it! |
| 456 |
|
| 457 |
Please note that [`notebook_launcher`] ignores the Accelerate config file, to launch based on the config use: |
| 458 |
|
| 459 |
```bash |
| 460 |
accelerate launch |
| 461 |
``` |
| 462 |
|
| 463 |
## Debugging |
| 464 |
|
| 465 |
A common issue when running the `notebook_launcher` is receiving a CUDA/XPU has already been initialized issue. This usually stems |
| 466 |
from an import or prior code in the notebook that makes a call to the PyTorch `torch.cuda` or `torch.xpu` sublibrary. To help narrow down what went wrong, |
| 467 |
you can launch the `notebook_launcher` with `ACCELERATE_DEBUG_MODE=yes` in your environment and an additional check |
| 468 |
will be made when spawning that a regular process can be created and utilize CUDA/XPU without issue. (Your CUDA/XPU code can still be ran afterwards). |
| 469 |
|
| 470 |
## Conclusion |
| 471 |
|
| 472 |
This notebook showed how to perform distributed training from inside of a Jupyter Notebook. Some key notes to remember: |
| 473 |
|
| 474 |
- Make sure to save any code that use CUDA/XPU (or CUDA/XPU imports) for the function passed to [`notebook_launcher`] |
| 475 |
- Set the `num_processes` to be the number of devices used for training (such as number of GPUs, XPUs, CPUs, TPUs, etc) |
| 476 |
- If using the TPU, declare your model outside the training loop function |