Package: accelerate
Run your *raw* PyTorch training script on any kind of deviceEasy to integrate🤗 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.🤗 Accelerate abstracts exactly and only the boilerplate code related to multi-GPUs/TPU/fp16 and leaves the rest of your code unchanged.Here is an example:import torchimport torch.nn.functional as Ffrom datasets import load_dataset+ from accelerate import Accelerator+ accelerator = Accelerator()- device = 'cpu'+ device = accelerator.devicemodel = torch.nn.Transformer().to(device)optimizer = torch.optim.Adam(model.parameters())dataset = load_dataset('my_dataset')data = torch.utils.data.DataLoader(dataset, shuffle=True)+ model, optimizer, data = accelerator.prepare(model, optimizer, data)model.train()for epoch in range(10):for source, targets in data:source = source.to(device)targets = targets.to(device)optimizer.zero_grad()output = model(source)loss = F.cross_entropy(output, targets)-         loss.backward()+         accelerator.backward(loss)optimizer.step()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).In particular, the same code can then be run without modification on your local machine for debugging or your training environment.🤗 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:import torchimport torch.nn.functional as Ffrom datasets import load_dataset+ from accelerate import Accelerator- device = 'cpu'+ accelerator = Accelerator()- model = torch.nn.Transformer().to(device)+ model = torch.nn.Transformer()optimizer = torch.optim.Adam(model.parameters())dataset = load_dataset('my_dataset')data = torch.utils.data.DataLoader(dataset, shuffle=True)+ model, optimizer, data = accelerator.prepare(model, optimizer, data)model.train()for epoch in range(10):for source, targets in data:-         source = source.to(device)-         targets = targets.to(device)optimizer.zero_grad()output = model(source)loss = F.cross_entropy(output, targets)-         loss.backward()+         accelerator.backward(loss)optimizer.step()Want to learn more? Check out thedocumentationor have a look at ourexamples.Launching script🤗 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 usetorch.distributed.runor to write a specific launcher for TPU training!
On your machine(s) just run:accelerateconfigand answer the questions asked. This will generate a config file that will be used automatically to properly set the default options when doingacceleratelaunchmy_script.py--args_to_my_scriptFor instance, here is how you would run the GLUE example on the MRPC task (from the root of the repo):acceleratelaunchexamples/nlp_example.pyThis CLI tool isoptional, and you can still usepython my_script.pyorpython -m torchrun my_script.pyat your convenience.You can also directly pass in the arguments you would totorchrunas arguments toaccelerate launchif you wish to not runaccelerate config.For example, here is how to launch on two GPUs:acceleratelaunch--multi_gpu--num_processes2examples/nlp_example.pyTo learn more, check the CLI documentation availablehere.Launching multi-CPU run using MPI🤗 Here is another way to launch multi-CPU run using MPI. You can learn how to install Open MPI onthis page. You can use Intel MPI or MVAPICH as well.
Once you have MPI setup on your cluster, just run:mpirun-np2pythonexamples/nlp_example.pyLaunching training using DeepSpeed🤗 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 justaccelerate config. However, if you desire to tweak your DeepSpeed related args from your Python script, we provide you theDeepSpeedPlugin.fromaccelerateimportAccelerator,DeepSpeedPlugin# deepspeed needs to know your gradient accumulation steps beforehand, so don't forget to pass it# Remember you still need to do gradient accumulation by yourself, just like you would have done without deepspeeddeepspeed_plugin=DeepSpeedPlugin(zero_stage=2,gradient_accumulation_steps=2)accelerator=Accelerator(mixed_precision='fp16',deepspeed_plugin=deepspeed_plugin)# How to save your 🤗 Transformer?accelerator.wait_for_everyone()unwrapped_model=accelerator.unwrap_model(model)unwrapped_model.save_pretrained(save_dir,save_function=accelerator.save,state_dict=accelerator.get_state_dict(model))Note: DeepSpeed support is experimental for now. In case you get into some problem, please open an issue.Launching your training from a notebook🤗 Accelerate also provides anotebook_launcherfunction 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 atraining_functionthen in your last cell, add:fromaccelerateimportnotebook_launchernotebook_launcher(training_function)An example can be found inthis notebook.Why should I use 🤗 Accelerate?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, theAcceleratorobject.Why shouldn't I use 🤗 Accelerate?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.Frameworks using 🤗 AccelerateIf 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:Amphionis 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.Animusis a minimalistic framework to run machine learning experiments. Animus highlights common "breakpoints" in ML experiments and provides a unified interface for them withinIExperiment.Catalystis 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 aRunnerto connect all parts of the experiment: hardware backend, data transformations, model training, and inference logic.fastaiis a PyTorch framework for Deep Learning that simplifies training fast and accurate neural nets using modern best practices. fastai provides aLearnerto handle the training, fine-tuning, and inference of deep learning algorithms.Finetuneris 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.InvokeAIis a creative engine for Stable Diffusion models, offering industry-leading WebUI, terminal usage support, and serves as the foundation for many commercial products.Korniais a differentiable library that allows classical computer vision to be integrated into deep learning models. Kornia provides aTrainerwith the specific purpose to train and fine-tune the supported deep learning algorithms within the library.Open Assistantis a chat-based assistant that understands tasks, can interact with their party systems, and retrieve information dynamically to do so.pytorch-acceleratedis a lightweight training library, with a streamlined feature set centered around a general-purposeTrainer, 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!Stable Diffusion web UIis an open-source browser-based easy-to-use interface based on the Gradio library for Stable Diffusion.torchkerasis 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.transformersas 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).InstallationThis repository is tested on Python 3.8+ and PyTorch 1.10.0+You should install 🤗 Accelerate in avirtual environment. If you're unfamiliar with Python virtual environments, check out theuser guide.First, create a virtual environment with the version of Python you're going to use and activate it.Then, you will need to install PyTorch: refer to theofficial installation pageregarding the specific install command for your platform. Then 🤗 Accelerate can be installed using pip as follows:pipinstallaccelerateSupported integrationsCPU onlymulti-CPU on one node (machine)multi-CPU on several nodes (machines)single GPUmulti-GPU on one node (machine)multi-GPU on several nodes (machines)TPUFP16/BFloat16 mixed precisionFP8 mixed precision withTransformer EngineDeepSpeed support (Experimental)PyTorch Fully Sharded Data Parallel (FSDP) support (Experimental)Megatron-LM support (Experimental)Citing 🤗 AccelerateIf you use 🤗 Accelerate in your publication, please cite it by using the following BibTeX entry.@Misc{accelerate,title={Accelerate: Training and inference at scale made simple, efficient and adaptable.},author={Sylvain Gugger and Lysandre Debut and Thomas Wolf and Philipp Schmid and Zachary Mueller and Sourab Mangrulkar and Marc Sun and Benjamin Bossan},howpublished={\url{https://github.com/huggingface/accelerate}},year={2022}}