Debian Codegraph @

README.md

raw
1 <!---
2 Copyright 2021 The HuggingFace Team. All rights reserved.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 -->
16
17 <p align="center">
18 <br>
19 <img src="https://raw.githubusercontent.com/huggingface/accelerate/main/docs/source/imgs/accelerate_logo.png" width="400"/>
20 <br>
21 <p>
22
23 <p align="center">
24 <!-- Uncomment when CircleCI is set up
25 <a href="https://circleci.com/gh/huggingface/accelerate"><img alt="Build" src="https://img.shields.io/circleci/build/github/huggingface/transformers/master"></a>
26 -->
27 <a href="https://github.com/huggingface/accelerate/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/github/license/huggingface/accelerate.svg?color=blue"></a>
28 <a href="https://huggingface.co/docs/accelerate/index.html"><img alt="Documentation" src="https://img.shields.io/website/http/huggingface.co/docs/accelerate/index.html.svg?down_color=red&down_message=offline&up_message=online"></a>
29 <a href="https://github.com/huggingface/accelerate/releases"><img alt="GitHub release" src="https://img.shields.io/github/release/huggingface/accelerate.svg"></a>
30 <a href="https://github.com/huggingface/accelerate/blob/main/CODE_OF_CONDUCT.md"><img alt="Contributor Covenant" src="https://img.shields.io/badge/Contributor%20Covenant-v2.0%20adopted-ff69b4.svg"></a>
31 </p>
32
33 <h3 align="center">
34 <p>Run your *raw* PyTorch training script on any kind of device
35 </h3>
36
37 <h3 align="center">
38 <a href="https://hf.co/course"><img src="https://raw.githubusercontent.com/huggingface/accelerate/main/docs/source/imgs/course_banner.png"></a>
39 </h3>
40
41 ## Easy to integrate
42
43 🤗 Accelerate was created for PyTorch users who like to write the training loop of PyTorch models but are reluctant to write and maintain the boilerplate code needed to use multi-GPUs/TPU/fp16.
44
45 🤗 Accelerate abstracts exactly and only the boilerplate code related to multi-GPUs/TPU/fp16 and leaves the rest of your code unchanged.
46
47 Here is an example:
48
49 ```diff
50 import torch
51 import torch.nn.functional as F
52 from datasets import load_dataset
53 + from accelerate import Accelerator
54
55 + accelerator = Accelerator()
56 - device = 'cpu'
57 + device = accelerator.device
58
59 model = torch.nn.Transformer().to(device)
60 optimizer = torch.optim.Adam(model.parameters())
61
62 dataset = load_dataset('my_dataset')
63 data = torch.utils.data.DataLoader(dataset, shuffle=True)
64
65 + model, optimizer, data = accelerator.prepare(model, optimizer, data)
66
67 model.train()
68 for epoch in range(10):
69 for source, targets in data:
70 source = source.to(device)
71 targets = targets.to(device)
72
73 optimizer.zero_grad()
74
75 output = model(source)
76 loss = F.cross_entropy(output, targets)
77
78 - loss.backward()
79 + accelerator.backward(loss)
80
81 optimizer.step()
82 ```
83
84 As you can see in this example, by adding 5-lines to any standard PyTorch training script you can now run on any kind of single or distributed node setting (single CPU, single GPU, multi-GPUs and TPUs) as well as with or without mixed precision (fp8, fp16, bf16).
85
86 In particular, the same code can then be run without modification on your local machine for debugging or your training environment.
87
88 🤗 Accelerate even handles the device placement for you (which requires a few more changes to your code, but is safer in general), so you can even simplify your training loop further:
89
90 ```diff
91 import torch
92 import torch.nn.functional as F
93 from datasets import load_dataset
94 + from accelerate import Accelerator
95
96 - device = 'cpu'
97 + accelerator = Accelerator()
98
99 - model = torch.nn.Transformer().to(device)
100 + model = torch.nn.Transformer()
101 optimizer = torch.optim.Adam(model.parameters())
102
103 dataset = load_dataset('my_dataset')
104 data = torch.utils.data.DataLoader(dataset, shuffle=True)
105
106 + model, optimizer, data = accelerator.prepare(model, optimizer, data)
107
108 model.train()
109 for epoch in range(10):
110 for source, targets in data:
111 - source = source.to(device)
112 - targets = targets.to(device)
113
114 optimizer.zero_grad()
115
116 output = model(source)
117 loss = F.cross_entropy(output, targets)
118
119 - loss.backward()
120 + accelerator.backward(loss)
121
122 optimizer.step()
123 ```
124
125 Want to learn more? Check out the [documentation](https://huggingface.co/docs/accelerate) or have a look at our [examples](https://github.com/huggingface/accelerate/tree/main/examples).
126
127 ## Launching script
128
129 🤗 Accelerate also provides an optional CLI tool that allows you to quickly configure and test your training environment before launching the scripts. No need to remember how to use `torch.distributed.run` or to write a specific launcher for TPU training!
130 On your machine(s) just run:
131
132 ```bash
133 accelerate config
134 ```
135
136 and answer the questions asked. This will generate a config file that will be used automatically to properly set the default options when doing
137
138 ```bash
139 accelerate launch my_script.py --args_to_my_script
140 ```
141
142 For instance, here is how you would run the GLUE example on the MRPC task (from the root of the repo):
143
144 ```bash
145 accelerate launch examples/nlp_example.py
146 ```
147
148 This CLI tool is **optional**, and you can still use `python my_script.py` or `python -m torchrun my_script.py` at your convenience.
149
150 You can also directly pass in the arguments you would to `torchrun` as arguments to `accelerate launch` if you wish to not run` accelerate config`.
151
152 For example, here is how to launch on two GPUs:
153
154 ```bash
155 accelerate launch --multi_gpu --num_processes 2 examples/nlp_example.py
156 ```
157
158 To learn more, check the CLI documentation available [here](https://huggingface.co/docs/accelerate/package_reference/cli).
159
160 Or view the configuration zoo [here](https://github.com/huggingface/accelerate/blob/main/examples/config_yaml_templates/)
161
162 ## Launching multi-CPU run using MPI
163
164 🤗 Here is another way to launch multi-CPU run using MPI. You can learn how to install Open MPI on [this page](https://www.open-mpi.org/faq/?category=building#easy-build). You can use Intel MPI or MVAPICH as well.
165 Once you have MPI setup on your cluster, just run:
166 ```bash
167 accelerate config
168 ```
169 Answer the questions that are asked, selecting to run using multi-CPU, and answer "yes" when asked if you want accelerate to launch mpirun.
170 Then, use `accelerate launch` with your script like:
171 ```bash
172 accelerate launch examples/nlp_example.py
173 ```
174 Alternatively, you can use mpirun directly, without using the CLI like:
175 ```bash
176 mpirun -np 2 python examples/nlp_example.py
177 ```
178
179 ## Launching training using DeepSpeed
180
181 🤗 Accelerate supports training on single/multiple GPUs using DeepSpeed. To use it, you don't need to change anything in your training code; you can set everything using just `accelerate config`. However, if you desire to tweak your DeepSpeed related args from your Python script, we provide you the `DeepSpeedPlugin`.
182
183 ```python
184 from accelerate import Accelerator, DeepSpeedPlugin
185
186 # deepspeed needs to know your gradient accumulation steps beforehand, so don't forget to pass it
187 # Remember you still need to do gradient accumulation by yourself, just like you would have done without deepspeed
188 deepspeed_plugin = DeepSpeedPlugin(zero_stage=2, gradient_accumulation_steps=2)
189 accelerator = Accelerator(mixed_precision='fp16', deepspeed_plugin=deepspeed_plugin)
190
191 # How to save your 🤗 Transformer?
192 accelerator.wait_for_everyone()
193 unwrapped_model = accelerator.unwrap_model(model)
194 unwrapped_model.save_pretrained(save_dir, save_function=accelerator.save, state_dict=accelerator.get_state_dict(model))
195 ```
196
197 Note: DeepSpeed support is experimental for now. In case you get into some problem, please open an issue.
198
199 ## Launching your training from a notebook
200
201 🤗 Accelerate also provides a `notebook_launcher` function you can use in a notebook to launch a distributed training. This is especially useful for Colab or Kaggle notebooks with a TPU backend. Just define your training loop in a `training_function` then in your last cell, add:
202
203 ```python
204 from accelerate import notebook_launcher
205
206 notebook_launcher(training_function)
207 ```
208
209 An example can be found in [this notebook](https://github.com/huggingface/notebooks/blob/main/examples/accelerate_examples/simple_nlp_example.ipynb). [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/accelerate_examples/simple_nlp_example.ipynb)
210
211 ## Why should I use 🤗 Accelerate?
212
213 You should use 🤗 Accelerate when you want to easily run your training scripts in a distributed environment without having to renounce full control over your training loop. This is not a high-level framework above PyTorch, just a thin wrapper so you don't have to learn a new library. In fact, the whole API of 🤗 Accelerate is in one class, the `Accelerator` object.
214
215 ## Why shouldn't I use 🤗 Accelerate?
216
217 You shouldn't use 🤗 Accelerate if you don't want to write a training loop yourself. There are plenty of high-level libraries above PyTorch that will offer you that, 🤗 Accelerate is not one of them.
218
219 ## Frameworks using 🤗 Accelerate
220
221 If you like the simplicity of 🤗 Accelerate but would prefer a higher-level abstraction around its capabilities, some frameworks and libraries that are built on top of 🤗 Accelerate are listed below:
222
223 * [Amphion](https://github.com/open-mmlab/Amphion) is a toolkit for Audio, Music, and Speech Generation. Its purpose is to support reproducible research and help junior researchers and engineers get started in the field of audio, music, and speech generation research and development.
224 * [Animus](https://github.com/Scitator/animus) is a minimalistic framework to run machine learning experiments. Animus highlights common "breakpoints" in ML experiments and provides a unified interface for them within [IExperiment](https://github.com/Scitator/animus/blob/main/animus/core.py#L76).
225 * [Catalyst](https://github.com/catalyst-team/catalyst#getting-started) is a PyTorch framework for Deep Learning Research and Development. It focuses on reproducibility, rapid experimentation, and codebase reuse so you can create something new rather than write yet another train loop. Catalyst provides a [Runner](https://catalyst-team.github.io/catalyst/api/core.html#runner) to connect all parts of the experiment: hardware backend, data transformations, model training, and inference logic.
226 * [fastai](https://github.com/fastai/fastai#installing) is a PyTorch framework for Deep Learning that simplifies training fast and accurate neural nets using modern best practices. fastai provides a [Learner](https://docs.fast.ai/learner.html#Learner) to handle the training, fine-tuning, and inference of deep learning algorithms.
227 * [Finetuner](https://github.com/jina-ai/finetuner) is a service that enables models to create higher-quality embeddings for semantic search, visual similarity search, cross-modal text<->image search, recommendation systems, clustering, duplication detection, anomaly detection, or other uses.
228 * [InvokeAI](https://github.com/invoke-ai/InvokeAI) is a creative engine for Stable Diffusion models, offering industry-leading WebUI, terminal usage support, and serves as the foundation for many commercial products.
229 * [Kornia](https://kornia.readthedocs.io/en/latest/get-started/introduction.html) is a differentiable library that allows classical computer vision to be integrated into deep learning models. Kornia provides a [Trainer](https://kornia.readthedocs.io/en/latest/x.html#kornia.x.Trainer) with the specific purpose to train and fine-tune the supported deep learning algorithms within the library.
230 * [Open Assistant](https://projects.laion.ai/Open-Assistant/) is a chat-based assistant that understands tasks, can interact with their party systems, and retrieve information dynamically to do so.
231 * [pytorch-accelerated](https://github.com/Chris-hughes10/pytorch-accelerated) is a lightweight training library, with a streamlined feature set centered around a general-purpose [Trainer](https://pytorch-accelerated.readthedocs.io/en/latest/trainer.html), that places a huge emphasis on simplicity and transparency; enabling users to understand exactly what is going on under the hood, but without having to write and maintain the boilerplate themselves!
232 * [Stable Diffusion web UI](https://github.com/AUTOMATIC1111/stable-diffusion-webui) is an open-source browser-based easy-to-use interface based on the Gradio library for Stable Diffusion.
233 * [torchkeras](https://github.com/lyhue1991/torchkeras) is a simple tool for training pytorch model just in a keras style, a dynamic and beautiful plot is provided in notebook to monitor your loss or metric.
234 * [transformers](https://github.com/huggingface/transformers) as a tool for helping train state-of-the-art machine learning models in PyTorch, Tensorflow, and JAX. (Accelerate is the backend for the PyTorch side).
235
236
237 ## Installation
238
239 This repository is tested on Python 3.8+ and PyTorch 1.10.0+
240
241 You should install 🤗 Accelerate in a [virtual environment](https://docs.python.org/3/library/venv.html). If you're unfamiliar with Python virtual environments, check out the [user guide](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/).
242
243 First, create a virtual environment with the version of Python you're going to use and activate it.
244
245 Then, you will need to install PyTorch: refer to the [official installation page](https://pytorch.org/get-started/locally/#start-locally) regarding the specific install command for your platform. Then 🤗 Accelerate can be installed using pip as follows:
246
247 ```bash
248 pip install accelerate
249 ```
250
251 ## Supported integrations
252
253 - CPU only
254 - multi-CPU on one node (machine)
255 - multi-CPU on several nodes (machines)
256 - single GPU
257 - multi-GPU on one node (machine)
258 - multi-GPU on several nodes (machines)
259 - TPU
260 - FP16/BFloat16 mixed precision
261 - FP8 mixed precision with [Transformer Engine](https://github.com/NVIDIA/TransformerEngine) or [MS-AMP](https://github.com/Azure/MS-AMP/)
262 - DeepSpeed support (Experimental)
263 - PyTorch Fully Sharded Data Parallel (FSDP) support (Experimental)
264 - Megatron-LM support (Experimental)
265
266 ## Citing 🤗 Accelerate
267
268 If you use 🤗 Accelerate in your publication, please cite it by using the following BibTeX entry.
269
270 ```bibtex
271 @Misc{accelerate,
272 title = {Accelerate: Training and inference at scale made simple, efficient and adaptable.},
273 author = {Sylvain Gugger and Lysandre Debut and Thomas Wolf and Philipp Schmid and Zachary Mueller and Sourab Mangrulkar and Marc Sun and Benjamin Bossan},
274 howpublished = {\url{https://github.com/huggingface/accelerate}},
275 year = {2022}
276 }
277 ```