{"id":13442837,"url":"https://github.com/huggingface/accelerate","last_synced_at":"2026-03-04T22:01:24.523Z","repository":{"id":37052022,"uuid":"308638334","full_name":"huggingface/accelerate","owner":"huggingface","description":"🚀 A simple way to launch, train, and use PyTorch models on almost any device and distributed configuration, automatic mixed precision (including fp8), and easy-to-configure FSDP and DeepSpeed support","archived":false,"fork":false,"pushed_at":"2025-05-12T15:57:58.000Z","size":5515,"stargazers_count":8701,"open_issues_count":113,"forks_count":1097,"subscribers_count":97,"default_branch":"main","last_synced_at":"2025-05-12T16:53:28.856Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://huggingface.co/docs/accelerate","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/huggingface.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-10-30T13:27:12.000Z","updated_at":"2025-05-12T16:14:15.000Z","dependencies_parsed_at":"2024-05-21T15:59:16.029Z","dependency_job_id":"4f46de56-56af-4684-9c34-90e6846cd527","html_url":"https://github.com/huggingface/accelerate","commit_stats":{"total_commits":1121,"total_committers":194,"mean_commits":5.778350515463917,"dds":0.6636931311329171,"last_synced_commit":"c3ec7ff5a9e1e3bddd3be0061e6362ff1bcb08a1"},"previous_names":[],"tags_count":72,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/huggingface%2Faccelerate","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/huggingface%2Faccelerate/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/huggingface%2Faccelerate/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/huggingface%2Faccelerate/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/huggingface","download_url":"https://codeload.github.com/huggingface/accelerate/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253818307,"owners_count":21969146,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T03:01:51.916Z","updated_at":"2026-03-04T22:01:23.828Z","avatar_url":"https://github.com/huggingface.png","language":"Python","funding_links":[],"categories":["Python","Frameworks-for-Training","Pytorch \u0026 related libraries｜Pytorch \u0026 相关库","Frameworks for Training","Deep Learning Framework","分布式机器学习","Pytorch \u0026 related libraries","Optimizations and fine-tuning","Fine-Tuning \u0026 Training","⚙️ Systems and Multi-GPU Engineering","🤗 Official Libraries","Computation and Communication Optimisation","Training","Official Resources","Optimization Tools","2. Libraries \u0026 Frameworks","Training \u0026 Fine-Tuning","1. Core Frameworks \u0026 Libraries"],"sub_categories":["Popular-LLM","Other libraries｜其他库:","High-Level DL APIs","Other libraries:","Training Infrastructure","Frameworks for Training","Python","Training Frameworks"],"readme":"\u003c!---\nCopyright 2021 The HuggingFace Team. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n--\u003e\n\n\u003cp align=\"center\"\u003e\n    \u003cbr\u003e\n    \u003cimg src=\"https://raw.githubusercontent.com/huggingface/accelerate/main/docs/source/imgs/accelerate_logo.png\" width=\"400\"/\u003e\n    \u003cbr\u003e\n\u003cp\u003e\n\n\u003cp align=\"center\"\u003e\n    \u003c!-- Uncomment when CircleCI is set up\n    \u003ca href=\"https://circleci.com/gh/huggingface/accelerate\"\u003e\u003cimg alt=\"Build\" src=\"https://img.shields.io/circleci/build/github/huggingface/transformers/master\"\u003e\u003c/a\u003e\n    --\u003e\n    \u003ca href=\"https://github.com/huggingface/accelerate/blob/main/LICENSE\"\u003e\u003cimg alt=\"License\" src=\"https://img.shields.io/github/license/huggingface/accelerate.svg?color=blue\"\u003e\u003c/a\u003e\n    \u003ca href=\"https://huggingface.co/docs/accelerate/index.html\"\u003e\u003cimg alt=\"Documentation\" src=\"https://img.shields.io/website/http/huggingface.co/docs/accelerate/index.html.svg?down_color=red\u0026down_message=offline\u0026up_message=online\"\u003e\u003c/a\u003e\n    \u003ca href=\"https://github.com/huggingface/accelerate/releases\"\u003e\u003cimg alt=\"GitHub release\" src=\"https://img.shields.io/github/release/huggingface/accelerate.svg\"\u003e\u003c/a\u003e\n    \u003ca href=\"https://github.com/huggingface/accelerate/blob/main/CODE_OF_CONDUCT.md\"\u003e\u003cimg alt=\"Contributor Covenant\" src=\"https://img.shields.io/badge/Contributor%20Covenant-v2.0%20adopted-ff69b4.svg\"\u003e\u003c/a\u003e\n\u003c/p\u003e\n\n\u003ch3 align=\"center\"\u003e\n\u003cp\u003eRun your *raw* PyTorch training script on any kind of device\n\u003c/h3\u003e\n\n\u003ch3 align=\"center\"\u003e\n    \u003ca href=\"https://hf.co/course\"\u003e\u003cimg src=\"https://raw.githubusercontent.com/huggingface/accelerate/main/docs/source/imgs/course_banner.png\"\u003e\u003c/a\u003e\n\u003c/h3\u003e\n\n## Easy to integrate\n\n🤗 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.\n\n🤗 Accelerate abstracts exactly and only the boilerplate code related to multi-GPUs/TPU/fp16 and leaves the rest of your code unchanged.\n\nHere is an example:\n\n```diff\n  import torch\n  import torch.nn.functional as F\n  from datasets import load_dataset\n+ from accelerate import Accelerator\n\n+ accelerator = Accelerator()\n- device = 'cpu'\n+ device = accelerator.device\n\n  model = torch.nn.Transformer().to(device)\n  optimizer = torch.optim.Adam(model.parameters())\n\n  dataset = load_dataset('my_dataset')\n  data = torch.utils.data.DataLoader(dataset, shuffle=True)\n\n+ model, optimizer, data = accelerator.prepare(model, optimizer, data)\n\n  model.train()\n  for epoch in range(10):\n      for source, targets in data:\n          source = source.to(device)\n          targets = targets.to(device)\n\n          optimizer.zero_grad()\n\n          output = model(source)\n          loss = F.cross_entropy(output, targets)\n\n-         loss.backward()\n+         accelerator.backward(loss)\n\n          optimizer.step()\n```\n\nAs 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).\n\nIn particular, the same code can then be run without modification on your local machine for debugging or your training environment.\n\n🤗 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:\n\n```diff\n  import torch\n  import torch.nn.functional as F\n  from datasets import load_dataset\n+ from accelerate import Accelerator\n\n- device = 'cpu'\n+ accelerator = Accelerator()\n\n- model = torch.nn.Transformer().to(device)\n+ model = torch.nn.Transformer()\n  optimizer = torch.optim.Adam(model.parameters())\n\n  dataset = load_dataset('my_dataset')\n  data = torch.utils.data.DataLoader(dataset, shuffle=True)\n\n+ model, optimizer, data = accelerator.prepare(model, optimizer, data)\n\n  model.train()\n  for epoch in range(10):\n      for source, targets in data:\n-         source = source.to(device)\n-         targets = targets.to(device)\n\n          optimizer.zero_grad()\n\n          output = model(source)\n          loss = F.cross_entropy(output, targets)\n\n-         loss.backward()\n+         accelerator.backward(loss)\n\n          optimizer.step()\n```\n\nWant 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).\n\n## Launching script\n\n🤗 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!\nOn your machine(s) just run:\n\n```bash\naccelerate config\n```\n\nand answer the questions asked. This will generate a config file that will be used automatically to properly set the default options when doing\n\n```bash\naccelerate launch my_script.py --args_to_my_script\n``` \n\nFor instance, here is how you would run the GLUE example on the MRPC task (from the root of the repo):\n\n```bash\naccelerate launch examples/nlp_example.py\n```\n\nThis CLI tool is **optional**, and you can still use `python my_script.py` or `python -m torchrun my_script.py` at your convenience.\n\nYou can also directly pass in the arguments you would to `torchrun` as arguments to `accelerate launch` if you wish to not run` accelerate config`.\n\nFor example, here is how to launch on two GPUs:\n\n```bash\naccelerate launch --multi_gpu --num_processes 2 examples/nlp_example.py\n```\n\nTo learn more, check the CLI documentation available [here](https://huggingface.co/docs/accelerate/package_reference/cli).\n\nOr view the configuration zoo [here](https://github.com/huggingface/accelerate/blob/main/examples/config_yaml_templates/)\n\n## Launching multi-CPU run using MPI\n\n🤗 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.\nOnce you have MPI setup on your cluster, just run:\n```bash\naccelerate config\n```\nAnswer the questions that are asked, selecting to run using multi-CPU, and answer \"yes\" when asked if you want accelerate to launch mpirun.\nThen, use `accelerate launch` with your script like:\n```bash\naccelerate launch examples/nlp_example.py\n```\nAlternatively, you can use mpirun directly, without using the CLI like:\n```bash\nmpirun -np 2 python examples/nlp_example.py\n```\n\n## Launching training using DeepSpeed\n\n🤗 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`.\n\n```python\nfrom accelerate import Accelerator, DeepSpeedPlugin\n\n# deepspeed needs to know your gradient accumulation steps beforehand, so don't forget to pass it\n# Remember you still need to do gradient accumulation by yourself, just like you would have done without deepspeed\ndeepspeed_plugin = DeepSpeedPlugin(zero_stage=2, gradient_accumulation_steps=2)\naccelerator = Accelerator(mixed_precision='fp16', deepspeed_plugin=deepspeed_plugin)\n\n# How to save your 🤗 Transformer?\naccelerator.wait_for_everyone()\nunwrapped_model = accelerator.unwrap_model(model)\nunwrapped_model.save_pretrained(save_dir, save_function=accelerator.save, state_dict=accelerator.get_state_dict(model))\n```\n\nNote: DeepSpeed support is experimental for now. In case you get into some problem, please open an issue.\n\n## Launching your training from a notebook\n\n🤗 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:\n\n```python\nfrom accelerate import notebook_launcher\n\nnotebook_launcher(training_function)\n```\n\nAn 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)\n\n## Why should I use 🤗 Accelerate?\n\nYou 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.\n\n## Why shouldn't I use 🤗 Accelerate?\n\nYou 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.\n\n## Frameworks using 🤗 Accelerate\n\nIf 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:\n\n* [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.\n* [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).\n* [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.\n* [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.\n* [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\u003c-\u003eimage search, recommendation systems, clustering, duplication detection, anomaly detection, or other uses.\n* [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.\n* [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.\n* [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. \n* [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!\n* [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.\n* [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.\n* [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).\n\n\n## Installation\n\nThis repository is tested on Python 3.8+ and PyTorch 1.10.0+\n\nYou 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/).\n\nFirst, create a virtual environment with the version of Python you're going to use and activate it.\n\nThen, 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:\n\n```bash\npip install accelerate\n```\n\n## Supported integrations\n\n- CPU only\n- multi-CPU on one node (machine)\n- multi-CPU on several nodes (machines)\n- single GPU\n- multi-GPU on one node (machine)\n- multi-GPU on several nodes (machines)\n- TPU\n- FP16/BFloat16 mixed precision\n- FP8 mixed precision with [Transformer Engine](https://github.com/NVIDIA/TransformerEngine) or [MS-AMP](https://github.com/Azure/MS-AMP/)\n- DeepSpeed support (Experimental)\n- PyTorch Fully Sharded Data Parallel (FSDP) support (Experimental)\n- Megatron-LM support (Experimental)\n\n## Citing 🤗 Accelerate\n\nIf you use 🤗 Accelerate in your publication, please cite it by using the following BibTeX entry.\n\n```bibtex\n@Misc{accelerate,\n  title =        {Accelerate: Training and inference at scale made simple, efficient and adaptable.},\n  author =       {Sylvain Gugger and Lysandre Debut and Thomas Wolf and Philipp Schmid and Zachary Mueller and Sourab Mangrulkar and Marc Sun and Benjamin Bossan},\n  howpublished = {\\url{https://github.com/huggingface/accelerate}},\n  year =         {2022}\n}\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhuggingface%2Faccelerate","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhuggingface%2Faccelerate","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhuggingface%2Faccelerate/lists"}