Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- lib/python3.12/site-packages/accelerate-1.7.0.dist-info/INSTALLERAdded+1
- lib/python3.12/site-packages/accelerate-1.7.0.dist-info/LICENSEAdded+201
- lib/python3.12/site-packages/accelerate-1.7.0.dist-info/METADATAAdded+382
- lib/python3.12/site-packages/accelerate-1.7.0.dist-info/RECORDAdded+177
- lib/python3.12/site-packages/accelerate-1.7.0.dist-info/REQUESTEDAdded
- lib/python3.12/site-packages/accelerate-1.7.0.dist-info/WHEELAdded+5
- lib/python3.12/site-packages/accelerate-1.7.0.dist-info/entry_points.txtAdded+6
- lib/python3.12/site-packages/accelerate-1.7.0.dist-info/top_level.txtAdded+1
- lib/python3.12/site-packages/accelerate/__init__.pyAdded+50
- lib/python3.12/site-packages/accelerate/accelerator.pyAdded
- lib/python3.12/site-packages/accelerate/big_modeling.pyAdded+749
- lib/python3.12/site-packages/accelerate/checkpointing.pyAdded+319
- lib/python3.12/site-packages/accelerate/commands/__init__.pyAdded+13
- lib/python3.12/site-packages/accelerate/commands/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/accelerate/commands/__pycache__/accelerate_cli.cpython-312.pycAdded
- lib/python3.12/site-packages/accelerate/commands/__pycache__/env.cpython-312.pycAdded
- lib/python3.12/site-packages/accelerate/commands/__pycache__/estimate.cpython-312.pycAdded
- lib/python3.12/site-packages/accelerate/commands/__pycache__/launch.cpython-312.pycAdded
- lib/python3.12/site-packages/accelerate/commands/__pycache__/merge.cpython-312.pycAdded
- lib/python3.12/site-packages/accelerate/commands/__pycache__/test.cpython-312.pycAdded
- lib/python3.12/site-packages/accelerate/commands/__pycache__/to_fsdp2.cpython-312.pycAdded
- lib/python3.12/site-packages/accelerate/commands/__pycache__/tpu.cpython-312.pycAdded
- lib/python3.12/site-packages/accelerate/commands/__pycache__/utils.cpython-312.pycAdded
- lib/python3.12/site-packages/accelerate/commands/accelerate_cli.pyAdded+54
- lib/python3.12/site-packages/accelerate/commands/config/__init__.pyAdded+52
- lib/python3.12/site-packages/accelerate/commands/config/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/accelerate/commands/config/__pycache__/cluster.cpython-312.pycAdded
- lib/python3.12/site-packages/accelerate/commands/config/__pycache__/config.cpython-312.pycAdded
- lib/python3.12/site-packages/accelerate/commands/config/__pycache__/config_args.cpython-312.pycAdded
- lib/python3.12/site-packages/accelerate/commands/config/__pycache__/config_utils.cpython-312.pycAdded
- lib/python3.12/site-packages/accelerate/commands/config/__pycache__/default.cpython-312.pycAdded
- lib/python3.12/site-packages/accelerate/commands/config/__pycache__/sagemaker.cpython-312.pycAdded
- lib/python3.12/site-packages/accelerate/commands/config/__pycache__/update.cpython-312.pycAdded
- lib/python3.12/site-packages/accelerate/commands/config/cluster.pyAdded+869
- lib/python3.12/site-packages/accelerate/commands/config/config.pyAdded+89
- lib/python3.12/site-packages/accelerate/commands/config/config_args.pyAdded+252
- lib/python3.12/site-packages/accelerate/commands/config/config_utils.pyAdded+122
- lib/python3.12/site-packages/accelerate/commands/config/default.pyAdded+163
- lib/python3.12/site-packages/accelerate/commands/config/sagemaker.pyAdded+274
- lib/python3.12/site-packages/accelerate/commands/config/update.pyAdded+63
- lib/python3.12/site-packages/accelerate/commands/env.pyAdded+131
- lib/python3.12/site-packages/accelerate/commands/estimate.pyAdded+312
- lib/python3.12/site-packages/accelerate/commands/launch.pyAdded+1208
- lib/python3.12/site-packages/accelerate/commands/menu/__init__.pyAdded+14
- lib/python3.12/site-packages/accelerate/commands/menu/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/accelerate/commands/menu/__pycache__/cursor.cpython-312.pycAdded
- lib/python3.12/site-packages/accelerate/commands/menu/__pycache__/helpers.cpython-312.pycAdded
- lib/python3.12/site-packages/accelerate/commands/menu/__pycache__/input.cpython-312.pycAdded
- lib/python3.12/site-packages/accelerate/commands/menu/__pycache__/keymap.cpython-312.pycAdded
- lib/python3.12/site-packages/accelerate/commands/menu/__pycache__/selection_menu.cpython-312.pycAdded
1pip123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382Metadata-Version: 2.1Name: accelerateVersion: 1.7.0Summary: AccelerateHome-page: https://github.com/huggingface/accelerateAuthor: The HuggingFace teamAuthor-email: zach.mueller@huggingface.coLicense: ApacheKeywords: deep learningClassifier: Development Status :: 5 - Production/StableClassifier: Intended Audience :: DevelopersClassifier: Intended Audience :: EducationClassifier: Intended Audience :: Science/ResearchClassifier: License :: OSI Approved :: Apache Software LicenseClassifier: Operating System :: OS IndependentClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3.9Classifier: Topic :: Scientific/Engineering :: Artificial IntelligenceRequires-Python: >=3.9.0Description-Content-Type: text/markdownLicense-File: LICENSERequires-Dist: numpy<3.0.0,>=1.17Requires-Dist: packaging>=20.0Requires-Dist: psutilRequires-Dist: pyyamlRequires-Dist: torch>=2.0.0Requires-Dist: huggingface-hub>=0.21.0Requires-Dist: safetensors>=0.4.3Provides-Extra: deepspeedRequires-Dist: deepspeed; extra == "deepspeed"Provides-Extra: devRequires-Dist: black~=23.1; extra == "dev"Requires-Dist: hf-doc-builder>=0.3.0; extra == "dev"Requires-Dist: ruff~=0.11.2; extra == "dev"Requires-Dist: pytest<=8.0.0,>=7.2.0; extra == "dev"Requires-Dist: pytest-xdist; extra == "dev"Requires-Dist: pytest-subtests; extra == "dev"Requires-Dist: parameterized; extra == "dev"Requires-Dist: pytest-order; extra == "dev"Requires-Dist: datasets; extra == "dev"Requires-Dist: diffusers; extra == "dev"Requires-Dist: evaluate; extra == "dev"Requires-Dist: torchdata>=0.8.0; extra == "dev"Requires-Dist: torchpippy>=0.2.0; extra == "dev"Requires-Dist: transformers; extra == "dev"Requires-Dist: scipy; extra == "dev"Requires-Dist: scikit-learn; extra == "dev"Requires-Dist: tqdm; extra == "dev"Requires-Dist: bitsandbytes; extra == "dev"Requires-Dist: timm; extra == "dev"Requires-Dist: rich; extra == "dev"Provides-Extra: docsProvides-Extra: qualityRequires-Dist: black~=23.1; extra == "quality"Requires-Dist: hf-doc-builder>=0.3.0; extra == "quality"Requires-Dist: ruff~=0.11.2; extra == "quality"Provides-Extra: richRequires-Dist: rich; extra == "rich"Provides-Extra: sagemakerRequires-Dist: sagemaker; extra == "sagemaker"Provides-Extra: test_devRequires-Dist: datasets; extra == "test-dev"Requires-Dist: diffusers; extra == "test-dev"Requires-Dist: evaluate; extra == "test-dev"Requires-Dist: torchdata>=0.8.0; extra == "test-dev"Requires-Dist: torchpippy>=0.2.0; extra == "test-dev"Requires-Dist: transformers; extra == "test-dev"Requires-Dist: scipy; extra == "test-dev"Requires-Dist: scikit-learn; extra == "test-dev"Requires-Dist: tqdm; extra == "test-dev"Requires-Dist: bitsandbytes; extra == "test-dev"Requires-Dist: timm; extra == "test-dev"Provides-Extra: test_fp8Requires-Dist: torchao; extra == "test-fp8"Provides-Extra: test_prodRequires-Dist: pytest<=8.0.0,>=7.2.0; extra == "test-prod"Requires-Dist: pytest-xdist; extra == "test-prod"Requires-Dist: pytest-subtests; extra == "test-prod"Requires-Dist: parameterized; extra == "test-prod"Requires-Dist: pytest-order; extra == "test-prod"Provides-Extra: test_trackersRequires-Dist: wandb; extra == "test-trackers"Requires-Dist: comet-ml; extra == "test-trackers"Requires-Dist: tensorboard; extra == "test-trackers"Requires-Dist: dvclive; extra == "test-trackers"Requires-Dist: mlflow; extra == "test-trackers"Requires-Dist: matplotlib; extra == "test-trackers"Provides-Extra: testingRequires-Dist: pytest<=8.0.0,>=7.2.0; extra == "testing"Requires-Dist: pytest-xdist; extra == "testing"Requires-Dist: pytest-subtests; extra == "testing"Requires-Dist: parameterized; extra == "testing"Requires-Dist: pytest-order; extra == "testing"Requires-Dist: datasets; extra == "testing"Requires-Dist: diffusers; extra == "testing"Requires-Dist: evaluate; extra == "testing"Requires-Dist: torchdata>=0.8.0; extra == "testing"Requires-Dist: torchpippy>=0.2.0; extra == "testing"Requires-Dist: transformers; extra == "testing"Requires-Dist: scipy; extra == "testing"Requires-Dist: scikit-learn; extra == "testing"Requires-Dist: tqdm; extra == "testing"Requires-Dist: bitsandbytes; extra == "testing"Requires-Dist: timm; extra == "testing"
<!---Copyright 2021 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License.-->
<p align="center"> <br> <img src="https://raw.githubusercontent.com/huggingface/accelerate/main/docs/source/imgs/accelerate_logo.png" width="400"/> <br><p>
<p align="center"> <!-- Uncomment when CircleCI is set up <a href="https://circleci.com/gh/huggingface/accelerate"><img alt="Build" src="https://img.shields.io/circleci/build/github/huggingface/transformers/master"></a> --> <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> <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> <a href="https://github.com/huggingface/accelerate/releases"><img alt="GitHub release" src="https://img.shields.io/github/release/huggingface/accelerate.svg"></a> <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></p>
<h3 align="center"><p>Run your *raw* PyTorch training script on any kind of device</h3>
<h3 align="center"> <a href="https://hf.co/course"><img src="https://raw.githubusercontent.com/huggingface/accelerate/main/docs/source/imgs/course_banner.png"></a></h3>
## Easy 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:
```diff import torch import torch.nn.functional as F from datasets import load_dataset+ from accelerate import Accelerator
+ accelerator = Accelerator()- device = 'cpu'+ device = accelerator.device
model = 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:
```diff import torch import torch.nn.functional as F from 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 the [documentation](https://huggingface.co/docs/accelerate) or have a look at our [examples](https://github.com/huggingface/accelerate/tree/main/examples).
## 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 use `torch.distributed.run` or to write a specific launcher for TPU training!On your machine(s) just run:
```bashaccelerate config```
and answer the questions asked. This will generate a config file that will be used automatically to properly set the default options when doing
```bashaccelerate launch my_script.py --args_to_my_script```
For instance, here is how you would run the GLUE example on the MRPC task (from the root of the repo):
```bashaccelerate launch examples/nlp_example.py```
This CLI tool is **optional**, and you can still use `python my_script.py` or `python -m torchrun my_script.py` at your convenience.
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`.
For example, here is how to launch on two GPUs:
```bashaccelerate launch --multi_gpu --num_processes 2 examples/nlp_example.py```
To learn more, check the CLI documentation available [here](https://huggingface.co/docs/accelerate/package_reference/cli).
Or view the configuration zoo [here](https://github.com/huggingface/accelerate/blob/main/examples/config_yaml_templates/)
## 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 on [this page](https://www.open-mpi.org/faq/?category=building#easy-build). You can use Intel MPI or MVAPICH as well.Once you have MPI setup on your cluster, just run:```bashaccelerate config```Answer the questions that are asked, selecting to run using multi-CPU, and answer "yes" when asked if you want accelerate to launch mpirun.Then, use `accelerate launch` with your script like:```bashaccelerate launch examples/nlp_example.py```Alternatively, you can use mpirun directly, without using the CLI like:```bashmpirun -np 2 python examples/nlp_example.py```
## Launching 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 just `accelerate config`. However, if you desire to tweak your DeepSpeed related args from your Python script, we provide you the `DeepSpeedPlugin`.
```pythonfrom accelerate import Accelerator, 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 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:
```pythonfrom accelerate import notebook_launcher
notebook_launcher(training_function)```
An example can be found in [this notebook](https://github.com/huggingface/notebooks/blob/main/examples/accelerate_examples/simple_nlp_example.ipynb). [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/accelerate_examples/simple_nlp_example.ipynb)
## 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, the `Accelerator` object.
## 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 🤗 Accelerate
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:
* [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.* [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).* [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.* [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.* [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.* [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.* [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.* [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. * [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!* [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.* [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.* [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).
## Installation
This repository is tested on Python 3.8+ and PyTorch 1.10.0+
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/).
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 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:
```bashpip install accelerate```
## Supported integrations
- CPU only- multi-CPU on one node (machine)- multi-CPU on several nodes (machines)- single GPU- multi-GPU on one node (machine)- multi-GPU on several nodes (machines)- TPU- FP16/BFloat16 mixed precision- FP8 mixed precision with [Transformer Engine](https://github.com/NVIDIA/TransformerEngine) or [MS-AMP](https://github.com/Azure/MS-AMP/)- DeepSpeed support (Experimental)- PyTorch Fully Sharded Data Parallel (FSDP) support (Experimental)- Megatron-LM support (Experimental)
## Citing 🤗 Accelerate
If you use 🤗 Accelerate in your publication, please cite it by using the following BibTeX entry.
```bibtex@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}}```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177../../../bin/accelerate,sha256=c1wvf3H-k_L4tPnGX-XJg6WjN-gXaWNL5vZQ135LI6I,269
../../../bin/accelerate-config,sha256=_W21OVf-14rQkJiDAXxKnqrC4Ty4PO9wzVPe7dp_LEc,261
../../../bin/accelerate-estimate-memory,sha256=NpxmelW1G5wWZKFvbMPayrm-zUERPFTF7AwjoQiEkCw,263
../../../bin/accelerate-launch,sha256=_77xdrxokfW2zuZ7LX5Nr-Ex9CoCQMRcUqGTE_EImrs,261
../../../bin/accelerate-merge-weights,sha256=WWSDTcMy5pPVGPPBk2TF1EioBPiDQ4hDLFKDVtqiNtE,260
accelerate-1.7.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
accelerate-1.7.0.dist-info/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
accelerate-1.7.0.dist-info/METADATA,sha256=Uh2USvM41iRR_WxMnmlQVVt8jrf8oGLwiyqvHNfRO1o,19490
accelerate-1.7.0.dist-info/RECORD,,
accelerate-1.7.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
accelerate-1.7.0.dist-info/WHEEL,sha256=GV9aMThwP_4oNCtvEC2ec3qUYutgWeAzklro_0m4WJQ,91
accelerate-1.7.0.dist-info/entry_points.txt,sha256=Vpy8gUGfZ-1VnM2229fb8CpJNLBdMH_wtJ9PQ7b_2tQ,296
accelerate-1.7.0.dist-info/top_level.txt,sha256=esVfdxTidsjQ90zsN_rPpjLFJ4ijRlx4mnLrG09hlt4,11
accelerate/__init__.py,sha256=mXUQGHBk-xdH1kg9XYR2xoW3DW5L5lz-7JI3mNlL5QY,1504
accelerate/__pycache__/__init__.cpython-312.pyc,,
accelerate/__pycache__/accelerator.cpython-312.pyc,,
accelerate/__pycache__/big_modeling.cpython-312.pyc,,
accelerate/__pycache__/checkpointing.cpython-312.pyc,,
accelerate/__pycache__/data_loader.cpython-312.pyc,,
accelerate/__pycache__/hooks.cpython-312.pyc,,
accelerate/__pycache__/inference.cpython-312.pyc,,
accelerate/__pycache__/launchers.cpython-312.pyc,,
accelerate/__pycache__/local_sgd.cpython-312.pyc,,
accelerate/__pycache__/logging.cpython-312.pyc,,
accelerate/__pycache__/memory_utils.cpython-312.pyc,,
accelerate/__pycache__/optimizer.cpython-312.pyc,,
accelerate/__pycache__/scheduler.cpython-312.pyc,,
accelerate/__pycache__/state.cpython-312.pyc,,
accelerate/__pycache__/tracking.cpython-312.pyc,,
accelerate/accelerator.py,sha256=B0JUgaTHvWkTCL1TOSG8h0JRSjS-YvbatdTAWXKRZuw,174281
accelerate/big_modeling.py,sha256=bqqO4Lw00YErTup7MUM6saOVHRFvMNOdNqAwg96fBG0,34765
accelerate/checkpointing.py,sha256=BaDOrpQzRI2U1BvN2vK4lepTRNNqbxGd4QPa1zOShoc,13612
accelerate/commands/__init__.py,sha256=m1PPTDT4ziIAvM0-FDSgIMIZ69Konn126s6LwuzH6v8,606
accelerate/commands/__pycache__/__init__.cpython-312.pyc,,
accelerate/commands/__pycache__/accelerate_cli.cpython-312.pyc,,
accelerate/commands/__pycache__/env.cpython-312.pyc,,
accelerate/commands/__pycache__/estimate.cpython-312.pyc,,
accelerate/commands/__pycache__/launch.cpython-312.pyc,,
accelerate/commands/__pycache__/merge.cpython-312.pyc,,
accelerate/commands/__pycache__/test.cpython-312.pyc,,
accelerate/commands/__pycache__/to_fsdp2.cpython-312.pyc,,
accelerate/commands/__pycache__/tpu.cpython-312.pyc,,
accelerate/commands/__pycache__/utils.cpython-312.pyc,,
accelerate/commands/accelerate_cli.py,sha256=SkwFad6Z1ZsGjtm7TiXFq8je-akshp_0WxX_6rGSBw8,1972
accelerate/commands/config/__init__.py,sha256=iJK8dgj3pc5Vdr1E7UuGoFu-BlybyXLxYDoTg9gXngE,1645
accelerate/commands/config/__pycache__/__init__.cpython-312.pyc,,
accelerate/commands/config/__pycache__/cluster.cpython-312.pyc,,
accelerate/commands/config/__pycache__/config.cpython-312.pyc,,
accelerate/commands/config/__pycache__/config_args.cpython-312.pyc,,
accelerate/commands/config/__pycache__/config_utils.cpython-312.pyc,,
accelerate/commands/config/__pycache__/default.cpython-312.pyc,,
accelerate/commands/config/__pycache__/sagemaker.cpython-312.pyc,,
accelerate/commands/config/__pycache__/update.cpython-312.pyc,,
accelerate/commands/config/cluster.py,sha256=8Mka4XTatMrFlxZjidvepRTLYgdJOX7ut9_4pLlmS7k,37537
accelerate/commands/config/config.py,sha256=FuRlQvOjgATEtyqOSsGD-KEtOCvACOHjs2C-krrtldk,3035
accelerate/commands/config/config_args.py,sha256=hJo7E3J_T7MPNkgtyNjPilJuH-wJK09mGWF6CvGFYIQ,9970
accelerate/commands/config/config_utils.py,sha256=lbV9iKAVSF5bUyQDGpzFduhH5JENYgAilPpRLLlCEq8,3299
accelerate/commands/config/default.py,sha256=UY0dQ7w1peBkQe8QDCm3XJrTnsRcm_G-_hf44NzNAbU,6213
accelerate/commands/config/sagemaker.py,sha256=SRLup9XrV_Z-23A3d8gZbkqbonDcscMDDmbpmytCzbY,10636
accelerate/commands/config/update.py,sha256=NXW1J7GkUHpg71QlIXsmMB_0z8S8IZo2FWax5POwrhc,2395
accelerate/commands/env.py,sha256=gRGwtPhMMWmZ5NTMaMrgHXaOzBV6SvAtP78TuuJvC6g,4336
accelerate/commands/estimate.py,sha256=Qduq4xudVyIede37BMEe1rNhXf-rfW-MHV2KtwxdfEA,12585
accelerate/commands/launch.py,sha256=-ODLdyV6zJ6yMsDKTNyUgUicYikX-VW2AA5wentb45g,46908
accelerate/commands/menu/__init__.py,sha256=uqSlBM0TFHBwzdv3p3SXfpAk1lZFp4h1a7mbBdscPHs,645
accelerate/commands/menu/__pycache__/__init__.cpython-312.pyc,,
accelerate/commands/menu/__pycache__/cursor.cpython-312.pyc,,
accelerate/commands/menu/__pycache__/helpers.cpython-312.pyc,,
accelerate/commands/menu/__pycache__/input.cpython-312.pyc,,
accelerate/commands/menu/__pycache__/keymap.cpython-312.pyc,,
accelerate/commands/menu/__pycache__/selection_menu.cpython-312.pyc,,
accelerate/commands/menu/cursor.py,sha256=-lmpJVAzvNc0c3EOtSuLoKB59zqylVCbYyWLPnrOmvQ,2028
accelerate/commands/menu/helpers.py,sha256=KrSB5fJjH4MUEUAQJ6bYaN16AYcnl9UalDrPD3DYeeg,1483
accelerate/commands/menu/input.py,sha256=T8Mdd-Y_OURgqfDV9qZh4Wf6hmT22AneNtJzj4JA1Rk,2512
accelerate/commands/menu/keymap.py,sha256=eXj-suyYs1m5dEHoUKN4mKAMLc8DWHnwhP6G6JSU0jQ,4086
accelerate/commands/menu/selection_menu.py,sha256=bxy-DHaKKC6SCToOlMBv5_z0MdUzylEg6Sio9OuV3GM,4921
accelerate/commands/merge.py,sha256=3Uo14LADvk8RJwZ_i6kIsGwWB3Ul5y8Uq47oHkDYqKU,2387
accelerate/commands/test.py,sha256=YrPYEaAACOGZ6btn2MV6NbMSEdBUcMWADLbQWaZSHtk,2149
accelerate/commands/to_fsdp2.py,sha256=gfbhoUT4qFB3LVDMNmckElgLG0yWm8aj_aofszeiJmM,5991
accelerate/commands/tpu.py,sha256=KyxDP7IuveidZrbW4rx2s8Ku3o_ptI6tzwr_R7ck0os,5548
accelerate/commands/utils.py,sha256=aT8xUCe2pCkFII7yZxcfaohEjgBAzMUM7WiD4UuWSOY,4150
accelerate/data_loader.py,sha256=yt6Rog94SMLJVMDsZjyrYuEGii5297p7N4jQM18bEZU,64850
accelerate/hooks.py,sha256=y4eN7blCjOkXY9_mVBmkgiTKqJfasAKrHOddEHj91Vg,33293
accelerate/inference.py,sha256=NLANdzXm5PwmDWbPYkFmoRoQSLLvuhfvIG33xfpapT0,7668
accelerate/launchers.py,sha256=GCj7y4qgK34k-VWi6EeM0DvXfsHBeGOZBfgTv9wi1zE,13724
accelerate/local_sgd.py,sha256=aCj_yqXK_FhhZRWEpzXIkgXBERH6fC3HyrC3nsOj1uA,4160
accelerate/logging.py,sha256=4XcgY_BV7Qn_enh2tZ-8fNtuaE_3n-LsYJbgwhRx_PI,5042
accelerate/memory_utils.py,sha256=3R5LoeHl6GgTZ-IMPrDZMdaEehWarGdPqODushb-6pg,862
accelerate/optimizer.py,sha256=oOz7vzvb_Np41V7iIPPcicf_sSm7g0utGsfZVkCseOM,8144
accelerate/scheduler.py,sha256=des_4M_Tt1W8gCYZZbLla0GHBEgJY3Wx2EGBQPTzeiY,4238
accelerate/state.py,sha256=ucpBxWn9nrE_6qTCKGAlziHASg3V712rQyEMScrwrlY,55922
accelerate/test_utils/__init__.py,sha256=ROl3bvBqmuI6ueRlPRNkNC-83yb6u6z_FFzrHJtq8rM,1809
accelerate/test_utils/__pycache__/__init__.cpython-312.pyc,,
accelerate/test_utils/__pycache__/examples.cpython-312.pyc,,
accelerate/test_utils/__pycache__/testing.cpython-312.pyc,,
accelerate/test_utils/__pycache__/training.cpython-312.pyc,,
accelerate/test_utils/examples.py,sha256=CO3SlkkrORUjroreoPfBPwfcNCDlHSgNWIt81iz2oQ8,7257
accelerate/test_utils/scripts/__init__.py,sha256=m1PPTDT4ziIAvM0-FDSgIMIZ69Konn126s6LwuzH6v8,606
accelerate/test_utils/scripts/__pycache__/__init__.cpython-312.pyc,,
accelerate/test_utils/scripts/__pycache__/test_cli.cpython-312.pyc,,
accelerate/test_utils/scripts/__pycache__/test_ddp_comm_hook.cpython-312.pyc,,
accelerate/test_utils/scripts/__pycache__/test_distributed_data_loop.cpython-312.pyc,,
accelerate/test_utils/scripts/__pycache__/test_merge_weights.cpython-312.pyc,,
accelerate/test_utils/scripts/__pycache__/test_notebook.cpython-312.pyc,,
accelerate/test_utils/scripts/__pycache__/test_ops.cpython-312.pyc,,
accelerate/test_utils/scripts/__pycache__/test_script.cpython-312.pyc,,
accelerate/test_utils/scripts/__pycache__/test_sync.cpython-312.pyc,,
accelerate/test_utils/scripts/external_deps/__init__.py,sha256=m1PPTDT4ziIAvM0-FDSgIMIZ69Konn126s6LwuzH6v8,606
accelerate/test_utils/scripts/external_deps/__pycache__/__init__.cpython-312.pyc,,
accelerate/test_utils/scripts/external_deps/__pycache__/test_checkpointing.cpython-312.pyc,,
accelerate/test_utils/scripts/external_deps/__pycache__/test_ds_multiple_model.cpython-312.pyc,,
accelerate/test_utils/scripts/external_deps/__pycache__/test_metrics.cpython-312.pyc,,
accelerate/test_utils/scripts/external_deps/__pycache__/test_peak_memory_usage.cpython-312.pyc,,
accelerate/test_utils/scripts/external_deps/__pycache__/test_performance.cpython-312.pyc,,
accelerate/test_utils/scripts/external_deps/__pycache__/test_pippy.cpython-312.pyc,,
accelerate/test_utils/scripts/external_deps/__pycache__/test_zero3_integration.cpython-312.pyc,,
accelerate/test_utils/scripts/external_deps/test_checkpointing.py,sha256=XHaNRmnrARd1izXFjWGi5UjYGas-4vqayW51jAHBPCA,10699
accelerate/test_utils/scripts/external_deps/test_ds_multiple_model.py,sha256=Cg4-h0B4UcOQ5CxXjIdrsPVR5fFsWCv24DqZGjXEwW8,13790
accelerate/test_utils/scripts/external_deps/test_metrics.py,sha256=Ev2XKaiwmznoxKujskAAuISGChW646MOiyf0CXEPb9Y,12168
accelerate/test_utils/scripts/external_deps/test_peak_memory_usage.py,sha256=9Yn9Rc7d-yWr1fU0RagASPG5l8vrKeHVYbuYABbA-fU,12498
accelerate/test_utils/scripts/external_deps/test_performance.py,sha256=4SW108BHEdpzDA_VY4B0GKKAdms4QxVlVywhZ-CZwRI,11721
accelerate/test_utils/scripts/external_deps/test_pippy.py,sha256=ocZntbmAduln2ma4LeEA9o-S8hla3YXCJ_A8hEcWHgs,4762
accelerate/test_utils/scripts/external_deps/test_zero3_integration.py,sha256=P9alBOHZ9Lfqs5LoRP7bCbXl-tnsNrBkvJZGseibBeA,1665
accelerate/test_utils/scripts/test_cli.py,sha256=qfk1aYFtdvYFCYPkl05602SNGvk08QTv0xZVVcFVtzM,833
accelerate/test_utils/scripts/test_ddp_comm_hook.py,sha256=k_-2MBjLKNdMGIcneTbuGd84K05Wp1GEQX6DUVF9UBw,3566
accelerate/test_utils/scripts/test_distributed_data_loop.py,sha256=RUWTwd7DIpr2fl7JtKOsvTjMiJioTxO8FdSr2Lw_5uI,15137
accelerate/test_utils/scripts/test_merge_weights.py,sha256=UQa5cR_gZK94fNuopsQ4FEAfTNEsTnlepCxXhboGEOg,6144
accelerate/test_utils/scripts/test_notebook.py,sha256=qfIy3IvH74-kGn8nadBn_k7qrviqvsxy5ijsnUhuY6o,3894
accelerate/test_utils/scripts/test_ops.py,sha256=Bcs-h8EMJwULTfbizlFN5qkv3JraWEpoSZWMn-HswiI,6265
accelerate/test_utils/scripts/test_script.py,sha256=A_AFMhT1lYqwd5AYMYdUe4B3Xf6e9cdiZwHpVVXFgUs,36460
accelerate/test_utils/scripts/test_sync.py,sha256=PDe8sYZLCL2LKjj_L9b-Bh2BjAjeii9EZ8sZNfuYx5s,18817
accelerate/test_utils/testing.py,sha256=b0x9j5ezzJbSPJp8nC22sHPQsttagLfZuYVD0g0Gdjo,28677
accelerate/test_utils/training.py,sha256=jO5YEIr34jAcnJ_9WNp_x3zuHzSam_I6IgMvmcGm7yI,6456
accelerate/tracking.py,sha256=ucpsoYAT3pVXgOfwDdXf6qTugY2-tk-EINvZtfmRitM,42756
accelerate/utils/__init__.py,sha256=R3I5NnGZPmAcom9RQvLgDxElXJHK21RCpBW5EUv9JuQ,7903
accelerate/utils/__pycache__/__init__.cpython-312.pyc,,
accelerate/utils/__pycache__/ao.cpython-312.pyc,,
accelerate/utils/__pycache__/bnb.cpython-312.pyc,,
accelerate/utils/__pycache__/constants.cpython-312.pyc,,
accelerate/utils/__pycache__/dataclasses.cpython-312.pyc,,
accelerate/utils/__pycache__/deepspeed.cpython-312.pyc,,
accelerate/utils/__pycache__/environment.cpython-312.pyc,,
accelerate/utils/__pycache__/fsdp_utils.cpython-312.pyc,,
accelerate/utils/__pycache__/imports.cpython-312.pyc,,
accelerate/utils/__pycache__/launch.cpython-312.pyc,,
accelerate/utils/__pycache__/megatron_lm.cpython-312.pyc,,
accelerate/utils/__pycache__/memory.cpython-312.pyc,,
accelerate/utils/__pycache__/modeling.cpython-312.pyc,,
accelerate/utils/__pycache__/offload.cpython-312.pyc,,
accelerate/utils/__pycache__/operations.cpython-312.pyc,,
accelerate/utils/__pycache__/other.cpython-312.pyc,,
accelerate/utils/__pycache__/random.cpython-312.pyc,,
accelerate/utils/__pycache__/rich.cpython-312.pyc,,
accelerate/utils/__pycache__/torch_xla.cpython-312.pyc,,
accelerate/utils/__pycache__/tqdm.cpython-312.pyc,,
accelerate/utils/__pycache__/transformer_engine.cpython-312.pyc,,
accelerate/utils/__pycache__/versions.cpython-312.pyc,,
accelerate/utils/ao.py,sha256=yfi84ywNpXsKZ6di4jbmtd6bIvRi9bmygr3giN92_Pg,4777
accelerate/utils/bnb.py,sha256=PdgdXwjhQ4Sg9orj4hlUiMQlPxSsdsiNfFVq4yBtl-g,20651
accelerate/utils/constants.py,sha256=A5KmcIry76B9p4Fa8CuI5ugv7bVcyTc5g4IBU1cvky0,3516
accelerate/utils/dataclasses.py,sha256=8ZF_sKfCh6XxBHhHQDI0arJrvk6vwXNtGXYz22xL5b4,133891
accelerate/utils/deepspeed.py,sha256=QYIXv5LwHXw7wBFFo-7a0t86MbwNAfieJkkBaLGA6wI,14064
accelerate/utils/environment.py,sha256=h0zacbBkAp9szltTf5-aTr5NcbVsQp7wl6DFWp8XNuI,15257
accelerate/utils/fsdp_utils.py,sha256=6vYmHrW3FBpsCTd3EInqfsSCtT80ohKm2qmflfRjJcg,36005
accelerate/utils/imports.py,sha256=YI1ebPJAuxarclENTfzvDPPGf6jeEKnVQ42taFPuqh0,16759
accelerate/utils/launch.py,sha256=sgJREpAYakqGJSSWB6ls2NKrYMZT_nzxg2VRAMpLAQ4,31721
accelerate/utils/megatron_lm.py,sha256=ZMxcYAdGnMWla2PtB04ctb9mhMfKUP8qLYusGNjyScU,58054
accelerate/utils/memory.py,sha256=Tuyr1Xnhk9Vz5HyCROBEZmrCmDz3-ArYoZN6xKFDnEc,7201
accelerate/utils/modeling.py,sha256=yA4tg20fnMixT-mZG7dmHPyZRwqT_P2I6Rj_pvVtMZM,94633
accelerate/utils/offload.py,sha256=VFaL8oSJzqZ_47VuUQ69xZi9bF2heRSFoOSnnOxbGXc,7825
accelerate/utils/operations.py,sha256=84SpXwKsbNHHePboL9gUqK6bA5vo0kyH_gLAdwnzE_s,31266
accelerate/utils/other.py,sha256=mgLiIDxqtAGAOwfWqXYmP-2sRZqq6q3Rbp1Lw5QR-z0,17369
accelerate/utils/random.py,sha256=Xv_ZJm9eaC2Q7rgZy9OpOunKuTingMiDQCH00qhNVxE,6220
accelerate/utils/rich.py,sha256=8JZX_uGMQX-BufdXxJpdne7BWd1KyLHSgbiGxrDMYr8,847
accelerate/utils/torch_xla.py,sha256=Pq1tuqN0X_pWDVza6YgjfO45uoJdoRVRForLeLQzFus,1908
accelerate/utils/tqdm.py,sha256=k8e9JnieTEQHCCNBaiBys7hPxWlEbyRASdIma-qy_X8,1657
accelerate/utils/transformer_engine.py,sha256=498Y3z2BkbybYLtBiuF_TJgt8Iii943s4wgRAV8FDC4,6372
accelerate/utils/versions.py,sha256=UgmcbjBm--6CIx1ZamSAMjAK_B_2l48LbeaNygqej8M,214912345Wheel-Version: 1.0Generator: setuptools (75.1.0)Root-Is-Purelib: trueTag: py3-none-any
123456[console_scripts]accelerate = accelerate.commands.accelerate_cli:mainaccelerate-config = accelerate.commands.config:mainaccelerate-estimate-memory = accelerate.commands.estimate:mainaccelerate-launch = accelerate.commands.launch:mainaccelerate-merge-weights = accelerate.commands.merge:main1accelerate1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950# Copyright 2020 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.__version__ = "1.7.0"
from .accelerator import Acceleratorfrom .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch,)from .data_loader import skip_first_batchesfrom .inference import prepare_pippyfrom .launchers import debug_launcher, notebook_launcherfrom .state import PartialStatefrom .utils import ( AutocastKwargs, DataLoaderConfiguration, DDPCommunicationHookType, DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, ProfileKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states,)
if is_rich_available(): from .utils import rich123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749# Copyright 2022 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import loggingimport osimport refrom contextlib import contextmanagerfrom functools import wrapsfrom typing import Optional, Union
import torchimport torch.nn as nn
from .hooks import ( AlignDevicesHook, CpuOffload, LayerwiseCastingHook, UserCpuOffloadHook, add_hook_to_module, attach_align_device_hook, attach_align_device_hook_on_blocks,)from .utils import ( OffloadedWeightsLoader, check_cuda_p2p_ib_support, check_device_map, extract_submodules_state_dict, find_tied_parameters, get_balanced_memory, infer_auto_device_map, is_bnb_available, is_mlu_available, is_musa_available, is_npu_available, is_sdaa_available, is_xpu_available, load_checkpoint_in_model, offload_state_dict, parse_flag_from_env, retie_parameters,)from .utils.constants import SUPPORTED_PYTORCH_LAYERS_FOR_UPCASTINGfrom .utils.other import recursive_getattr
logger = logging.getLogger(__name__)
@contextmanagerdef init_empty_weights(include_buffers: bool = None): """ A context manager under which models are initialized with all parameters on the meta device, therefore creating an empty model. Useful when just initializing the model would blow the available RAM.
Args: include_buffers (`bool`, *optional*): Whether or not to also put all buffers on the meta device while initializing.
Example:
```python import torch.nn as nn from accelerate import init_empty_weights
# Initialize a model with 100 billions parameters in no time and without using any RAM. with init_empty_weights(): tst = nn.Sequential(*[nn.Linear(10000, 10000) for _ in range(1000)]) ```
<Tip warning={true}>
Any model created under this context manager has no weights. As such you can't do something like `model.to(some_device)` with it. To load weights inside your empty model, see [`load_checkpoint_and_dispatch`]. Make sure to overwrite the default device_map param for [`load_checkpoint_and_dispatch`], otherwise dispatch is not called.
</Tip> """ if include_buffers is None: include_buffers = parse_flag_from_env("ACCELERATE_INIT_INCLUDE_BUFFERS", False) with init_on_device(torch.device("meta"), include_buffers=include_buffers) as f: yield f
@contextmanagerdef init_on_device(device: torch.device, include_buffers: bool = None): """ A context manager under which models are initialized with all parameters on the specified device.
Args: device (`torch.device`): Device to initialize all parameters on. include_buffers (`bool`, *optional*): Whether or not to also put all buffers on the meta device while initializing.
Example:
```python import torch.nn as nn from accelerate import init_on_device
with init_on_device(device=torch.device("cuda")): tst = nn.Linear(100, 100) # on `cuda` device ``` """ if include_buffers is None: include_buffers = parse_flag_from_env("ACCELERATE_INIT_INCLUDE_BUFFERS", False)
if include_buffers: with device: yield return
old_register_parameter = nn.Module.register_parameter if include_buffers: old_register_buffer = nn.Module.register_buffer
def register_empty_parameter(module, name, param): old_register_parameter(module, name, param) if param is not None: param_cls = type(module._parameters[name]) kwargs = module._parameters[name].__dict__ kwargs["requires_grad"] = param.requires_grad module._parameters[name] = param_cls(module._parameters[name].to(device), **kwargs)
def register_empty_buffer(module, name, buffer, persistent=True): old_register_buffer(module, name, buffer, persistent=persistent) if buffer is not None: module._buffers[name] = module._buffers[name].to(device)
# Patch tensor creation if include_buffers: tensor_constructors_to_patch = { torch_function_name: getattr(torch, torch_function_name) for torch_function_name in ["empty", "zeros", "ones", "full"] } else: tensor_constructors_to_patch = {}
def patch_tensor_constructor(fn): def wrapper(*args, **kwargs): kwargs["device"] = device return fn(*args, **kwargs)
return wrapper
try: nn.Module.register_parameter = register_empty_parameter if include_buffers: nn.Module.register_buffer = register_empty_buffer for torch_function_name in tensor_constructors_to_patch.keys(): setattr(torch, torch_function_name, patch_tensor_constructor(getattr(torch, torch_function_name))) yield finally: nn.Module.register_parameter = old_register_parameter if include_buffers: nn.Module.register_buffer = old_register_buffer for torch_function_name, old_torch_function in tensor_constructors_to_patch.items(): setattr(torch, torch_function_name, old_torch_function)
def cpu_offload( model: nn.Module, execution_device: Optional[torch.device] = None, offload_buffers: bool = False, state_dict: Optional[dict[str, torch.Tensor]] = None, preload_module_classes: Optional[list[str]] = None,): """ Activates full CPU offload for a model. As a result, all parameters of the model will be offloaded and only one copy of the state dict of the model will be kept. During the forward pass, parameters will be extracted from that state dict and put on the execution device passed as they are needed, then offloaded again.
Args: model (`torch.nn.Module`): The model to offload. execution_device (`torch.device`, *optional*): The device on which the forward pass of the model will be executed (should be a GPU). Will default to the model first parameter device. offload_buffers (`bool`, *optional*, defaults to `False`): Whether or not to offload the buffers with the model parameters. state_dict (`Dict[str, torch.Tensor]`, *optional*): The state dict of the model that will be kept on CPU. preload_module_classes (`List[str]`, *optional*): A list of classes whose instances should load all their weights (even in the submodules) at the beginning of the forward. This should only be used for classes that have submodules which are registered but not called directly during the forward, for instance if a `dense` linear layer is registered, but at forward, `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly. """ if execution_device is None: execution_device = next(iter(model.parameters())).device if state_dict is None: state_dict = {n: p.to("cpu") for n, p in model.state_dict().items()}
add_hook_to_module(model, AlignDevicesHook(io_same_device=True), append=True) attach_align_device_hook( model, execution_device=execution_device, offload=True, offload_buffers=offload_buffers, weights_map=state_dict, preload_module_classes=preload_module_classes, )
return model
def cpu_offload_with_hook( model: torch.nn.Module, execution_device: Optional[Union[int, str, torch.device]] = None, prev_module_hook: Optional[UserCpuOffloadHook] = None,): """ Offloads a model on the CPU and puts it back to an execution device when executed. The difference with [`cpu_offload`] is that the model stays on the execution device after the forward and is only offloaded again when the `offload` method of the returned `hook` is called. Useful for pipelines running a model in a loop.
Args: model (`torch.nn.Module`): The model to offload. execution_device(`str`, `int` or `torch.device`, *optional*): The device on which the model should be executed. Will default to the MPS device if it's available, then GPU 0 if there is a GPU, and finally to the CPU. prev_module_hook (`UserCpuOffloadHook`, *optional*): The hook sent back by this function for a previous model in the pipeline you are running. If passed, its offload method will be called just before the forward of the model to which this hook is attached.
Example:
```py model_1, hook_1 = cpu_offload_with_hook(model_1, cuda_device) model_2, hook_2 = cpu_offload_with_hook(model_2, cuda_device, prev_module_hook=hook_1) model_3, hook_3 = cpu_offload_with_hook(model_3, cuda_device, prev_module_hook=hook_2)
hid_1 = model_1(input) for i in range(50): # model1 is offloaded on the CPU at the first iteration, model 2 stays on the GPU for this whole loop. hid_2 = model_2(hid_1) # model2 is offloaded to the CPU just before this forward. hid_3 = model_3(hid_3)
# For model3, you need to manually call the hook offload method. hook_3.offload() ``` """ hook = CpuOffload(execution_device=execution_device, prev_module_hook=prev_module_hook) add_hook_to_module(model, hook, append=True) user_hook = UserCpuOffloadHook(model, hook) return model, user_hook
def disk_offload( model: nn.Module, offload_dir: Union[str, os.PathLike], execution_device: Optional[torch.device] = None, offload_buffers: bool = False, preload_module_classes: Optional[list[str]] = None,): """ Activates full disk offload for a model. As a result, all parameters of the model will be offloaded as memory-mapped array in a given folder. During the forward pass, parameters will be accessed from that folder and put on the execution device passed as they are needed, then offloaded again.
Args: model (`torch.nn.Module`): The model to offload. offload_dir (`str` or `os.PathLike`): The folder in which to offload the model weights (or where the model weights are already offloaded). execution_device (`torch.device`, *optional*): The device on which the forward pass of the model will be executed (should be a GPU). Will default to the model's first parameter device. offload_buffers (`bool`, *optional*, defaults to `False`): Whether or not to offload the buffers with the model parameters. preload_module_classes (`List[str]`, *optional*): A list of classes whose instances should load all their weights (even in the submodules) at the beginning of the forward. This should only be used for classes that have submodules which are registered but not called directly during the forward, for instance if a `dense` linear layer is registered, but at forward, `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly. """ if not os.path.isdir(offload_dir) or not os.path.isfile(os.path.join(offload_dir, "index.json")): offload_state_dict(offload_dir, model.state_dict()) if execution_device is None: execution_device = next(iter(model.parameters())).device weights_map = OffloadedWeightsLoader(save_folder=offload_dir)
add_hook_to_module(model, AlignDevicesHook(io_same_device=True), append=True) attach_align_device_hook( model, execution_device=execution_device, offload=True, offload_buffers=offload_buffers, weights_map=weights_map, preload_module_classes=preload_module_classes, )
return model
def dispatch_model( model: nn.Module, device_map: dict[str, Union[str, int, torch.device]], main_device: Optional[torch.device] = None, state_dict: Optional[dict[str, torch.Tensor]] = None, offload_dir: Optional[Union[str, os.PathLike]] = None, offload_index: Optional[dict[str, str]] = None, offload_buffers: bool = False, skip_keys: Optional[Union[str, list[str]]] = None, preload_module_classes: Optional[list[str]] = None, force_hooks: bool = False,): """ Dispatches a model according to a given device map. Layers of the model might be spread across GPUs, offloaded on the CPU or even the disk.
Args: model (`torch.nn.Module`): The model to dispatch. device_map (`Dict[str, Union[str, int, torch.device]]`): A dictionary mapping module names in the models `state_dict` to the device they should go to. Note that `"disk"` is accepted even if it's not a proper value for `torch.device`. main_device (`str`, `int` or `torch.device`, *optional*): The main execution device. Will default to the first device in the `device_map` different from `"cpu"` or `"disk"`. state_dict (`Dict[str, torch.Tensor]`, *optional*): The state dict of the part of the model that will be kept on CPU. offload_dir (`str` or `os.PathLike`): The folder in which to offload the model weights (or where the model weights are already offloaded). offload_index (`Dict`, *optional*): A dictionary from weight name to their information (`dtype`/ `shape` or safetensors filename). Will default to the index saved in `save_folder`. offload_buffers (`bool`, *optional*, defaults to `False`): Whether or not to offload the buffers with the model parameters. skip_keys (`str` or `List[str]`, *optional*): A list of keys to ignore when moving inputs or outputs between devices. preload_module_classes (`List[str]`, *optional*): A list of classes whose instances should load all their weights (even in the submodules) at the beginning of the forward. This should only be used for classes that have submodules which are registered but not called directly during the forward, for instance if a `dense` linear layer is registered, but at forward, `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly. force_hooks (`bool`, *optional*, defaults to `False`): Whether or not to force device hooks to be attached to the model even if all layers are dispatched to a single device. """ # Error early if the device map is incomplete. check_device_map(model, device_map)
# We need to force hook for quantized model that can't be moved with to() if getattr(model, "quantization_method", "bitsandbytes") == "bitsandbytes": # since bnb 0.43.2, we can move 4-bit model if getattr(model, "is_loaded_in_8bit", False) or ( getattr(model, "is_loaded_in_4bit", False) and not is_bnb_available(min_version="0.43.2") ): force_hooks = True
# We attach hooks if the device_map has at least 2 different devices or if # force_hooks is set to `True`. Otherwise, the model in already loaded # in the unique device and the user can decide where to dispatch the model. # If the model is quantized, we always force-dispatch the model if (len(set(device_map.values())) > 1) or force_hooks: if main_device is None: if set(device_map.values()) == {"cpu"} or set(device_map.values()) == {"cpu", "disk"}: main_device = "cpu" else: main_device = [d for d in device_map.values() if d not in ["cpu", "disk"]][0]
if main_device != "cpu": cpu_modules = [name for name, device in device_map.items() if device == "cpu"] if state_dict is None and len(cpu_modules) > 0: state_dict = extract_submodules_state_dict(model.state_dict(), cpu_modules)
disk_modules = [name for name, device in device_map.items() if device == "disk"] if offload_dir is None and offload_index is None and len(disk_modules) > 0: raise ValueError( "We need an `offload_dir` to dispatch this model according to this `device_map`, the following submodules " f"need to be offloaded: {', '.join(disk_modules)}." ) if ( len(disk_modules) > 0 and offload_index is None and (not os.path.isdir(offload_dir) or not os.path.isfile(os.path.join(offload_dir, "index.json"))) ): disk_state_dict = extract_submodules_state_dict(model.state_dict(), disk_modules) offload_state_dict(offload_dir, disk_state_dict)
execution_device = { name: main_device if device in ["cpu", "disk"] else device for name, device in device_map.items() } execution_device[""] = main_device offloaded_devices = ["disk"] if main_device == "cpu" or main_device == "mps" else ["cpu", "disk"] offload = {name: device in offloaded_devices for name, device in device_map.items()} save_folder = offload_dir if len(disk_modules) > 0 else None if state_dict is not None or save_folder is not None or offload_index is not None: device = main_device if offload_index is not None else None weights_map = OffloadedWeightsLoader( state_dict=state_dict, save_folder=save_folder, index=offload_index, device=device ) else: weights_map = None
# When dispatching the model's parameters to the devices specified in device_map, we want to avoid allocating memory several times for the # tied parameters. The dictionary tied_params_map keeps track of the already allocated data for a given tied parameter (represented by its # original pointer) on each devices. tied_params = find_tied_parameters(model)
tied_params_map = {} for group in tied_params: for param_name in group: # data_ptr() is enough here, as `find_tied_parameters` finds tied params simply by comparing `param1 is param2`, so we don't need # to care about views of tensors through storage_offset. data_ptr = recursive_getattr(model, param_name).data_ptr() tied_params_map[data_ptr] = {}
# Note: To handle the disk offloading case, we can not simply use weights_map[param_name].data_ptr() as the reference pointer, # as we have no guarantee that safetensors' `file.get_tensor()` will always give the same pointer.
attach_align_device_hook_on_blocks( model, execution_device=execution_device, offload=offload, offload_buffers=offload_buffers, weights_map=weights_map, skip_keys=skip_keys, preload_module_classes=preload_module_classes, tied_params_map=tied_params_map, )
# warn if there is any params on the meta device offloaded_devices_str = " and ".join( [device for device in set(device_map.values()) if device in ("cpu", "disk")] ) if len(offloaded_devices_str) > 0: logger.warning( f"Some parameters are on the meta device because they were offloaded to the {offloaded_devices_str}." )
# Attaching the hook may break tied weights, so we retie them retie_parameters(model, tied_params)
# add warning to cuda and to method def add_warning(fn, model): @wraps(fn) def wrapper(*args, **kwargs): warning_msg = "You shouldn't move a model that is dispatched using accelerate hooks." if str(fn.__name__) == "to": to_device = torch._C._nn._parse_to(*args, **kwargs)[0] if to_device is not None: logger.warning(warning_msg) else: logger.warning(warning_msg) for param in model.parameters(): if param.device == torch.device("meta"): raise RuntimeError("You can't move a model that has some modules offloaded to cpu or disk.") return fn(*args, **kwargs)
return wrapper
# Make sure to update _accelerate_added_attributes in hooks.py if you add any hook model.to = add_warning(model.to, model) if is_npu_available(): model.npu = add_warning(model.npu, model) elif is_mlu_available(): model.mlu = add_warning(model.mlu, model) elif is_sdaa_available(): model.sdaa = add_warning(model.sdaa, model) elif is_musa_available(): model.musa = add_warning(model.musa, model) elif is_xpu_available(): model.xpu = add_warning(model.xpu, model) else: model.cuda = add_warning(model.cuda, model)
# Check if we are using multi-gpus with RTX 4000 series use_multi_gpu = len([device for device in set(device_map.values()) if device not in ("cpu", "disk")]) > 1 if use_multi_gpu and not check_cuda_p2p_ib_support(): logger.warning( "We've detected an older driver with an RTX 4000 series GPU. These drivers have issues with P2P. " "This can affect the multi-gpu inference when using accelerate device_map." "Please make sure to update your driver to the latest version which resolves this." ) else: device = list(device_map.values())[0] # `torch.Tensor.to(<int num>)` is not supported by `torch_npu` (see this [issue](https://github.com/Ascend/pytorch/issues/16)). if is_npu_available() and isinstance(device, int): device = f"npu:{device}" elif is_mlu_available() and isinstance(device, int): device = f"mlu:{device}" elif is_sdaa_available() and isinstance(device, int): device = f"sdaa:{device}" elif is_musa_available() and isinstance(device, int): device = f"musa:{device}" if device != "disk": model.to(device) else: raise ValueError( "You are trying to offload the whole model to the disk. Please use the `disk_offload` function instead." ) # Convert OrderedDict back to dict for easier usage model.hf_device_map = dict(device_map) return model
def load_checkpoint_and_dispatch( model: nn.Module, checkpoint: Union[str, os.PathLike], device_map: Optional[Union[str, dict[str, Union[int, str, torch.device]]]] = None, max_memory: Optional[dict[Union[int, str], Union[int, str]]] = None, no_split_module_classes: Optional[list[str]] = None, offload_folder: Optional[Union[str, os.PathLike]] = None, offload_buffers: bool = False, dtype: Optional[Union[str, torch.dtype]] = None, offload_state_dict: Optional[bool] = None, skip_keys: Optional[Union[str, list[str]]] = None, preload_module_classes: Optional[list[str]] = None, force_hooks: bool = False, strict: bool = False, full_state_dict: bool = True, broadcast_from_rank0: bool = False,): """ Loads a (potentially sharded) checkpoint inside a model, potentially sending weights to a given device as they are loaded and adds the various hooks that will make this model run properly (even if split across devices).
Args: model (`torch.nn.Module`): The model in which we want to load a checkpoint. checkpoint (`str` or `os.PathLike`): The folder checkpoint to load. It can be: - a path to a file containing a whole model state dict - a path to a `.json` file containing the index to a sharded checkpoint - a path to a folder containing a unique `.index.json` file and the shards of a checkpoint. device_map (`Dict[str, Union[int, str, torch.device]]`, *optional*): A map that specifies where each submodule should go. It doesn't need to be refined to each parameter/buffer name, once a given module name is inside, every submodule of it will be sent to the same device.
To have Accelerate compute the most optimized `device_map` automatically, set `device_map="auto"`. For more information about each option see [here](../concept_guides/big_model_inference#designing-a-device-map). Defaults to None, which means [`dispatch_model`] will not be called. max_memory (`Dict`, *optional*): A dictionary device identifier to maximum memory. Will default to the maximum memory available for each GPU and the available CPU RAM if unset. no_split_module_classes (`List[str]`, *optional*): A list of layer class names that should never be split across device (for instance any layer that has a residual connection). offload_folder (`str` or `os.PathLike`, *optional*): If the `device_map` contains any value `"disk"`, the folder where we will offload weights. offload_buffers (`bool`, *optional*, defaults to `False`): In the layers that are offloaded on the CPU or the hard drive, whether or not to offload the buffers as well as the parameters. dtype (`str` or `torch.dtype`, *optional*): If provided, the weights will be converted to that type when loaded. offload_state_dict (`bool`, *optional*): If `True`, will temporarily offload the CPU state dict on the hard drive to avoid getting out of CPU RAM if the weight of the CPU state dict + the biggest shard does not fit. Will default to `True` if the device map picked contains `"disk"` values. skip_keys (`str` or `List[str]`, *optional*): A list of keys to ignore when moving inputs or outputs between devices. preload_module_classes (`List[str]`, *optional*): A list of classes whose instances should load all their weights (even in the submodules) at the beginning of the forward. This should only be used for classes that have submodules which are registered but not called directly during the forward, for instance if a `dense` linear layer is registered, but at forward, `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly. force_hooks (`bool`, *optional*, defaults to `False`): Whether or not to force device hooks to be attached to the model even if all layers are dispatched to a single device. strict (`bool`, *optional*, defaults to `False`): Whether to strictly enforce that the keys in the checkpoint state_dict match the keys of the model's state_dict. full_state_dict (`bool`, *optional*, defaults to `True`): if this is set to `True`, all the tensors in the loaded state_dict will be gathered. No ShardedTensor and DTensor will be in the loaded state_dict. broadcast_from_rank0 (`False`, *optional*, defaults to `False`): when the option is `True`, a distributed `ProcessGroup` must be initialized. rank0 should receive a full state_dict and will broadcast the tensors in the state_dict one by one to other ranks. Other ranks will receive the tensors and shard (if applicable) according to the local shards in the model.
Example:
```python >>> from accelerate import init_empty_weights, load_checkpoint_and_dispatch >>> from huggingface_hub import hf_hub_download >>> from transformers import AutoConfig, AutoModelForCausalLM
>>> # Download the Weights >>> checkpoint = "EleutherAI/gpt-j-6B" >>> weights_location = hf_hub_download(checkpoint, "pytorch_model.bin")
>>> # Create a model and initialize it with empty weights >>> config = AutoConfig.from_pretrained(checkpoint) >>> with init_empty_weights(): ... model = AutoModelForCausalLM.from_config(config)
>>> # Load the checkpoint and dispatch it to the right devices >>> model = load_checkpoint_and_dispatch( ... model, weights_location, device_map="auto", no_split_module_classes=["GPTJBlock"] ... ) ``` """ if isinstance(device_map, str) and device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: raise ValueError( "If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or 'sequential'." ) if isinstance(device_map, str): if device_map != "sequential": max_memory = get_balanced_memory( model, max_memory=max_memory, no_split_module_classes=no_split_module_classes, dtype=dtype, low_zero=(device_map == "balanced_low_0"), ) device_map = infer_auto_device_map( model, max_memory=max_memory, no_split_module_classes=no_split_module_classes, dtype=dtype, offload_buffers=offload_buffers, ) if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): offload_state_dict = True load_checkpoint_in_model( model, checkpoint, device_map=device_map, offload_folder=offload_folder, dtype=dtype, offload_state_dict=offload_state_dict, offload_buffers=offload_buffers, strict=strict, full_state_dict=full_state_dict, broadcast_from_rank0=broadcast_from_rank0, ) if device_map is None: return model return dispatch_model( model, device_map=device_map, offload_dir=offload_folder, offload_buffers=offload_buffers, skip_keys=skip_keys, preload_module_classes=preload_module_classes, force_hooks=force_hooks, )
def attach_layerwise_casting_hooks( module: torch.nn.Module, storage_dtype: torch.dtype, compute_dtype: torch.dtype, skip_modules_pattern: Union[str, tuple[str, ...]] = None, skip_modules_classes: Optional[tuple[type[torch.nn.Module], ...]] = None, non_blocking: bool = False,) -> None: r""" Applies layerwise casting to a given module. The module expected here is a PyTorch `nn.Module`. This is helpful for reducing memory requirements when one doesn't want to fully quantize a model. Model params can be kept in say, `torch.float8_e4m3fn` and upcasted to a higher precision like `torch.bfloat16` during forward pass and downcasted back to `torch.float8_e4m3fn` to realize memory savings.
Args: module (`torch.nn.Module`): The module whose leaf modules will be cast to a high precision dtype for computation, and to a low precision dtype for storage. storage_dtype (`torch.dtype`): The dtype to cast the module to before/after the forward pass for storage. compute_dtype (`torch.dtype`): The dtype to cast the module to during the forward pass for computation. skip_modules_pattern (`tuple[str, ...]`, defaults to `None`): A list of patterns to match the names of the modules to skip during the layerwise casting process. If set to `None` alongside `skip_modules_classes` being `None`, the layerwise casting is applied directly to the module instead of its internal submodules. skip_modules_classes (`tuple[type[torch.nn.Module], ...]`, defaults to `None`): A list of module classes to skip during the layerwise casting process. non_blocking (`bool`, defaults to `False`): If `True`, the weight casting operations are non-blocking.
Example:
```python >>> from accelerate.hooks import attach_layerwise_casting_hooks >>> from transformers import AutoModelForCausalLM >>> import torch
>>> # Model >>> checkpoint = "EleutherAI/gpt-j-6B" >>> model = AutoModelForCausalLM.from_pretrained(checkpoint)
>>> # Attach hooks and perform inference >>> attach_layerwise_casting_hooks(model, storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16) >>> with torch.no_grad(): ... model(...) ```
Users can also pass modules they want to avoid from getting downcasted.
```py >>> attach_layerwise_casting_hooks( ... model, storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16, skip_modules_pattern=["norm"] ... ) ``` """ _attach_layerwise_casting_hooks( module, storage_dtype, compute_dtype, skip_modules_pattern, skip_modules_classes, non_blocking )
def _attach_layerwise_casting_hooks( module: torch.nn.Module, storage_dtype: torch.dtype, compute_dtype: torch.dtype, skip_modules_pattern: Union[str, tuple[str, ...]] = None, skip_modules_classes: Optional[tuple[type[torch.nn.Module], ...]] = None, non_blocking: bool = False, _prefix: str = "",): should_skip = (skip_modules_classes is not None and isinstance(module, skip_modules_classes)) or ( skip_modules_pattern is not None and any(re.search(pattern, _prefix) for pattern in skip_modules_pattern) ) if should_skip: logger.debug(f'Skipping layerwise casting for layer "{_prefix}"') return
if isinstance(module, SUPPORTED_PYTORCH_LAYERS_FOR_UPCASTING): logger.debug(f'Applying layerwise casting to layer "{_prefix}"') add_hook_to_module( module, LayerwiseCastingHook(storage_dtype=storage_dtype, compute_dtype=compute_dtype, non_blocking=non_blocking), append=True, ) return
for name, submodule in module.named_children(): layer_name = f"{_prefix}.{name}" if _prefix else name _attach_layerwise_casting_hooks( submodule, storage_dtype, compute_dtype, skip_modules_pattern, skip_modules_classes, non_blocking, _prefix=layer_name, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319# Copyright 2022 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import randomfrom pathlib import Path
import numpy as npimport torchfrom safetensors.torch import load_modelfrom torch.cuda.amp import GradScaler
from .utils import ( MODEL_NAME, OPTIMIZER_NAME, RNG_STATE_NAME, SAFE_MODEL_NAME, SAFE_WEIGHTS_NAME, SAMPLER_NAME, SCALER_NAME, SCHEDULER_NAME, WEIGHTS_NAME, get_pretty_name, is_cuda_available, is_hpu_available, is_mlu_available, is_musa_available, is_sdaa_available, is_torch_xla_available, is_xpu_available, load, save,)
if is_torch_xla_available(): import torch_xla.core.xla_model as xm
from .logging import get_loggerfrom .state import PartialState
logger = get_logger(__name__)
def save_accelerator_state( output_dir: str, model_states: list[dict], optimizers: list, schedulers: list, dataloaders: list, process_index: int, step: int, scaler: GradScaler = None, save_on_each_node: bool = False, safe_serialization: bool = True,): """ Saves the current states of the models, optimizers, scaler, and RNG generators to a given directory.
<Tip>
If `safe_serialization` is `True`, models will be saved with `safetensors` while the rest are saved using native `pickle`.
</Tip>
Args: output_dir (`str` or `os.PathLike`): The name of the folder to save all relevant weights and states. model_states (`List[torch.nn.Module]`): A list of model states optimizers (`List[torch.optim.Optimizer]`): A list of optimizer instances schedulers (`List[torch.optim.lr_scheduler._LRScheduler]`): A list of learning rate schedulers dataloaders (`List[torch.utils.data.DataLoader]`): A list of dataloader instances to save their sampler states process_index (`int`): The current process index in the Accelerator state step (`int`): The current step in the internal step tracker scaler (`torch.amp.GradScaler`, *optional*): An optional gradient scaler instance to save; save_on_each_node (`bool`, *optional*): Whether to save on every node, or only the main node. safe_serialization (`bool`, *optional*, defaults to `True`): Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`). """ output_dir = Path(output_dir) # Model states for i, state in enumerate(model_states): weights_name = WEIGHTS_NAME if not safe_serialization else SAFE_WEIGHTS_NAME if i > 0: weights_name = weights_name.replace(".", f"_{i}.") output_model_file = output_dir.joinpath(weights_name) save(state, output_model_file, save_on_each_node=save_on_each_node, safe_serialization=safe_serialization) logger.info(f"Model weights saved in {output_model_file}") # Optimizer states for i, opt in enumerate(optimizers): state = opt.state_dict() optimizer_name = f"{OPTIMIZER_NAME}.bin" if i == 0 else f"{OPTIMIZER_NAME}_{i}.bin" output_optimizer_file = output_dir.joinpath(optimizer_name) save(state, output_optimizer_file, save_on_each_node=save_on_each_node, safe_serialization=False) logger.info(f"Optimizer state saved in {output_optimizer_file}") # Scheduler states for i, scheduler in enumerate(schedulers): state = scheduler.state_dict() scheduler_name = f"{SCHEDULER_NAME}.bin" if i == 0 else f"{SCHEDULER_NAME}_{i}.bin" output_scheduler_file = output_dir.joinpath(scheduler_name) save(state, output_scheduler_file, save_on_each_node=save_on_each_node, safe_serialization=False) logger.info(f"Scheduler state saved in {output_scheduler_file}") # DataLoader states for i, dataloader in enumerate(dataloaders): sampler_name = f"{SAMPLER_NAME}.bin" if i == 0 else f"{SAMPLER_NAME}_{i}.bin" output_sampler_file = output_dir.joinpath(sampler_name) # Only save if we have our custom sampler from .data_loader import IterableDatasetShard, SeedableRandomSampler
if isinstance(dataloader.dataset, IterableDatasetShard): sampler = dataloader.get_sampler() if isinstance(sampler, SeedableRandomSampler): save(sampler, output_sampler_file, save_on_each_node=save_on_each_node, safe_serialization=False) if getattr(dataloader, "use_stateful_dataloader", False): dataloader_state_dict_name = "dl_state_dict.bin" if i == 0 else f"dl_state_dict_{i}.bin" output_dataloader_state_dict_file = output_dir.joinpath(dataloader_state_dict_name) state_dict = dataloader.state_dict() torch.save(state_dict, output_dataloader_state_dict_file) logger.info(f"Sampler state for dataloader {i} saved in {output_sampler_file}")
# GradScaler state if scaler is not None: state = scaler.state_dict() output_scaler_file = output_dir.joinpath(SCALER_NAME) torch.save(state, output_scaler_file) logger.info(f"Gradient scaler state saved in {output_scaler_file}") # Random number generator states states = {} states_name = f"{RNG_STATE_NAME}_{process_index}.pkl" states["step"] = step states["random_state"] = random.getstate() states["numpy_random_seed"] = np.random.get_state() states["torch_manual_seed"] = torch.get_rng_state() if is_xpu_available(): states["torch_xpu_manual_seed"] = torch.xpu.get_rng_state_all() if is_mlu_available(): states["torch_mlu_manual_seed"] = torch.mlu.get_rng_state_all() elif is_sdaa_available(): states["torch_sdaa_manual_seed"] = torch.sdaa.get_rng_state_all() elif is_musa_available(): states["torch_musa_manual_seed"] = torch.musa.get_rng_state_all() if is_hpu_available(): states["torch_hpu_manual_seed"] = torch.hpu.get_rng_state_all() if is_cuda_available(): states["torch_cuda_manual_seed"] = torch.cuda.get_rng_state_all() if is_torch_xla_available(): states["xm_seed"] = xm.get_rng_state() output_states_file = output_dir.joinpath(states_name) torch.save(states, output_states_file) logger.info(f"Random states saved in {output_states_file}") return output_dir
def load_accelerator_state( input_dir, models, optimizers, schedulers, dataloaders, process_index, scaler=None, map_location=None, **load_model_func_kwargs,): """ Loads states of the models, optimizers, scaler, and RNG generators from a given directory.
Args: input_dir (`str` or `os.PathLike`): The name of the folder to load all relevant weights and states. models (`List[torch.nn.Module]`): A list of model instances optimizers (`List[torch.optim.Optimizer]`): A list of optimizer instances schedulers (`List[torch.optim.lr_scheduler._LRScheduler]`): A list of learning rate schedulers process_index (`int`): The current process index in the Accelerator state scaler (`torch.amp.GradScaler`, *optional*): An optional *GradScaler* instance to load map_location (`str`, *optional*): What device to load the optimizer state onto. Should be one of either "cpu" or "on_device". load_model_func_kwargs (`dict`, *optional*): Additional arguments that can be passed to the model's `load_state_dict` method.
Returns: `dict`: Contains the `Accelerator` attributes to override while loading the state. """ # stores the `Accelerator` attributes to override override_attributes = dict() if map_location not in [None, "cpu", "on_device"]: raise TypeError( "Unsupported optimizer map location passed, please choose one of `None`, `'cpu'`, or `'on_device'`" ) if map_location is None: map_location = "cpu" elif map_location == "on_device": map_location = PartialState().device
input_dir = Path(input_dir) # Model states for i, model in enumerate(models): ending = f"_{i}" if i > 0 else "" input_model_file = input_dir.joinpath(f"{SAFE_MODEL_NAME}{ending}.safetensors") if input_model_file.exists(): load_model(model, input_model_file, device=str(map_location), **load_model_func_kwargs) else: # Load with torch input_model_file = input_dir.joinpath(f"{MODEL_NAME}{ending}.bin") state_dict = load(input_model_file, map_location=map_location) model.load_state_dict(state_dict, **load_model_func_kwargs) logger.info("All model weights loaded successfully")
# Optimizer states for i, opt in enumerate(optimizers): optimizer_name = f"{OPTIMIZER_NAME}.bin" if i == 0 else f"{OPTIMIZER_NAME}_{i}.bin" input_optimizer_file = input_dir.joinpath(optimizer_name) optimizer_state = load(input_optimizer_file, map_location=map_location) optimizers[i].load_state_dict(optimizer_state) logger.info("All optimizer states loaded successfully")
# Scheduler states for i, scheduler in enumerate(schedulers): scheduler_name = f"{SCHEDULER_NAME}.bin" if i == 0 else f"{SCHEDULER_NAME}_{i}.bin" input_scheduler_file = input_dir.joinpath(scheduler_name) scheduler_state = load(input_scheduler_file) scheduler.load_state_dict(scheduler_state) logger.info("All scheduler states loaded successfully")
for i, dataloader in enumerate(dataloaders): sampler_name = f"{SAMPLER_NAME}.bin" if i == 0 else f"{SAMPLER_NAME}_{i}.bin" input_sampler_file = input_dir.joinpath(sampler_name) # Only load if we have our custom sampler from .data_loader import IterableDatasetShard, SeedableRandomSampler
if isinstance(dataloader.dataset, IterableDatasetShard): sampler = dataloader.get_sampler() if isinstance(sampler, SeedableRandomSampler): sampler = dataloader.set_sampler(load(input_sampler_file)) if getattr(dataloader, "use_stateful_dataloader", False): dataloader_state_dict_name = "dl_state_dict.bin" if i == 0 else f"dl_state_dict_{i}.bin" input_dataloader_state_dict_file = input_dir.joinpath(dataloader_state_dict_name) if input_dataloader_state_dict_file.exists(): state_dict = load(input_dataloader_state_dict_file) dataloader.load_state_dict(state_dict) logger.info("All dataloader sampler states loaded successfully")
# GradScaler state if scaler is not None: input_scaler_file = input_dir.joinpath(SCALER_NAME) scaler_state = load(input_scaler_file) scaler.load_state_dict(scaler_state) logger.info("GradScaler state loaded successfully")
# Random states try: states = load(input_dir.joinpath(f"{RNG_STATE_NAME}_{process_index}.pkl")) if "step" in states: override_attributes["step"] = states["step"] random.setstate(states["random_state"]) np.random.set_state(states["numpy_random_seed"]) torch.set_rng_state(states["torch_manual_seed"]) if is_xpu_available(): torch.xpu.set_rng_state_all(states["torch_xpu_manual_seed"]) if is_mlu_available(): torch.mlu.set_rng_state_all(states["torch_mlu_manual_seed"]) elif is_sdaa_available(): torch.sdaa.set_rng_state_all(states["torch_sdaa_manual_seed"]) elif is_musa_available(): torch.musa.set_rng_state_all(states["torch_musa_manual_seed"]) else: torch.cuda.set_rng_state_all(states["torch_cuda_manual_seed"]) if is_torch_xla_available(): xm.set_rng_state(states["xm_seed"]) logger.info("All random states loaded successfully") except Exception: logger.info("Could not load random states")
return override_attributes
def save_custom_state(obj, path, index: int = 0, save_on_each_node: bool = False): """ Saves the state of `obj` to `{path}/custom_checkpoint_{index}.pkl` """ # Should this be the right way to get a qual_name type value from `obj`? save_location = Path(path) / f"custom_checkpoint_{index}.pkl" logger.info(f"Saving the state of {get_pretty_name(obj)} to {save_location}") save(obj.state_dict(), save_location, save_on_each_node=save_on_each_node)
def load_custom_state(obj, path, index: int = 0): """ Loads the state of `obj` at `{path}/custom_checkpoint_{index}.pkl`. Will always set `weights_only=False` when loading the state. """ load_location = f"{path}/custom_checkpoint_{index}.pkl" logger.info(f"Loading the state of {get_pretty_name(obj)} from {load_location}") obj.load_state_dict(load(load_location, map_location="cpu", weights_only=False))12345678910111213# Copyright 2020 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354#!/usr/bin/env python
# Copyright 2021 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
from accelerate.commands.config import get_config_parserfrom accelerate.commands.env import env_command_parserfrom accelerate.commands.estimate import estimate_command_parserfrom accelerate.commands.launch import launch_command_parserfrom accelerate.commands.merge import merge_command_parserfrom accelerate.commands.test import test_command_parserfrom accelerate.commands.to_fsdp2 import to_fsdp2_command_parserfrom accelerate.commands.tpu import tpu_command_parserfrom accelerate.commands.utils import CustomArgumentParser
def main(): parser = CustomArgumentParser("Accelerate CLI tool", usage="accelerate <command> [<args>]", allow_abbrev=False) subparsers = parser.add_subparsers(help="accelerate command helpers")
# Register commands get_config_parser(subparsers=subparsers) estimate_command_parser(subparsers=subparsers) env_command_parser(subparsers=subparsers) launch_command_parser(subparsers=subparsers) merge_command_parser(subparsers=subparsers) tpu_command_parser(subparsers=subparsers) test_command_parser(subparsers=subparsers) to_fsdp2_command_parser(subparsers=subparsers)
# Let's go args = parser.parse_args()
if not hasattr(args, "func"): parser.print_help() exit(1)
# Run args.func(args)
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152#!/usr/bin/env python
# Copyright 2021 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import argparse
from .config import config_command_parserfrom .config_args import default_config_file, load_config_from_file # noqa: F401from .default import default_command_parserfrom .update import update_command_parser
def get_config_parser(subparsers=None): parent_parser = argparse.ArgumentParser(add_help=False, allow_abbrev=False) # The main config parser config_parser = config_command_parser(subparsers) # The subparser to add commands to subcommands = config_parser.add_subparsers(title="subcommands", dest="subcommand")
# Then add other parsers with the parent parser default_command_parser(subcommands, parents=[parent_parser]) update_command_parser(subcommands, parents=[parent_parser])
return config_parser
def main(): config_parser = get_config_parser() args = config_parser.parse_args()
if not hasattr(args, "func"): config_parser.print_help() exit(1)
# Run args.func(args)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869#!/usr/bin/env python
# Copyright 2021 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import os
from ...utils import ( ComputeEnvironment, DistributedType, is_deepspeed_available, is_fp8_available, is_hpu_available, is_mlu_available, is_mps_available, is_msamp_available, is_musa_available, is_npu_available, is_sdaa_available, is_transformer_engine_available, is_transformers_available, is_xpu_available,)from ...utils.constants import ( DEEPSPEED_MULTINODE_LAUNCHERS, FSDP2_STATE_DICT_TYPE, FSDP_AUTO_WRAP_POLICY, FSDP_BACKWARD_PREFETCH, FSDP_SHARDING_STRATEGY, FSDP_STATE_DICT_TYPE, TORCH_DYNAMO_MODES,)from .config_args import ClusterConfigfrom .config_utils import ( DYNAMO_BACKENDS, _ask_field, _ask_options, _convert_distributed_mode, _convert_dynamo_backend, _convert_fp8_backend, _convert_mixed_precision, _convert_yes_no_to_bool,)
def get_cluster_input(): distributed_type = _ask_options( "Which type of machine are you using?", [ "No distributed training", "multi-CPU", "multi-XPU", "multi-HPU", "multi-GPU", "multi-NPU", "multi-MLU", "multi-SDAA", "multi-MUSA", "TPU", ], _convert_distributed_mode, )
machine_rank = 0 num_machines = 1 num_processes = 1 gpu_ids = None main_process_ip = None main_process_port = None rdzv_backend = "static" same_network = True debug = False
if distributed_type in [ DistributedType.MULTI_GPU, DistributedType.MULTI_MLU, DistributedType.MULTI_SDAA, DistributedType.MULTI_MUSA, DistributedType.MULTI_NPU, DistributedType.MULTI_XPU, DistributedType.MULTI_CPU, DistributedType.MULTI_HPU, ]: num_machines = _ask_field( "How many different machines will you use (use more than 1 for multi-node training)? [1]: ", int, default=1, ) if num_machines > 1: machine_rank = _ask_options( "What is the rank of this machine?", list(range(num_machines)), int, ) main_process_ip = _ask_field( "What is the IP address of the machine that will host the main process? ", ) main_process_port = _ask_field( "What is the port you will use to communicate with the main process? ", int, ) same_network = _ask_field( "Are all the machines on the same local network? Answer `no` if nodes are on the cloud and/or on different network hosts [YES/no]: ", _convert_yes_no_to_bool, default=True, error_message="Please enter yes or no.", ) if not same_network: rdzv_backend = _ask_field( "What rendezvous backend will you use? ('static', 'c10d', ...): ", default="static" ) debug = _ask_field( "Should distributed operations be checked while running for errors? This can avoid timeout issues but will be slower. [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", )
if distributed_type == DistributedType.NO: use_cpu = _ask_field( "Do you want to run your training on CPU only (even if a GPU / Apple Silicon / Ascend NPU device is available)? [yes/NO]:", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", ) elif distributed_type == DistributedType.MULTI_CPU: use_cpu = True else: use_cpu = False
ipex_config = {} mpirun_config = {} if use_cpu or is_xpu_available(): ipex_config["ipex"] = _ask_field( "Do you want to use Intel PyTorch Extension (IPEX) to speed up training on CPU/XPU? [yes/NO]:", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", )
if use_cpu: if distributed_type == DistributedType.MULTI_CPU: use_mpirun = _ask_field( "Do you want accelerate to launch mpirun? [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", ) if use_mpirun: mpirun_hostfile = _ask_field( "Please enter the path to the hostfile to use with mpirun [~/hostfile]: ", str, default="~/hostfile", ) mpirun_config["mpirun_hostfile"] = os.path.expanduser(mpirun_hostfile.strip()) mpirun_config["mpirun_ccl"] = _ask_field("Enter the number of oneCCL worker threads [1]: ", default=1)
dynamo_config = {} use_dynamo = _ask_field( "Do you wish to optimize your script with torch dynamo?[yes/NO]:", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", ) if use_dynamo: prefix = "dynamo_" dynamo_config[prefix + "backend"] = _ask_options( "Which dynamo backend would you like to use?", [x.lower() for x in DYNAMO_BACKENDS], _convert_dynamo_backend, default=2, ) use_custom_options = _ask_field( "Do you want to customize the defaults sent to torch.compile? [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", )
if use_custom_options: dynamo_config[prefix + "mode"] = _ask_options( "Which mode do you want to use?", TORCH_DYNAMO_MODES, lambda x: TORCH_DYNAMO_MODES[int(x)], default=0, ) dynamo_config[prefix + "use_fullgraph"] = _ask_field( "Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", ) dynamo_config[prefix + "use_dynamic"] = _ask_field( "Do you want to enable dynamic shape tracing? [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", ) dynamo_config[prefix + "use_regional_compilation"] = _ask_field( "Do you want to enable regional compilation? [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", )
use_mps = not use_cpu and is_mps_available() deepspeed_config = {} if ( distributed_type in [ DistributedType.MULTI_GPU, DistributedType.MULTI_XPU, DistributedType.MULTI_HPU, DistributedType.MULTI_NPU, DistributedType.MULTI_MLU, DistributedType.MULTI_SDAA, DistributedType.MULTI_MUSA, DistributedType.NO, ] and not use_mps ): use_deepspeed = _ask_field( "Do you want to use DeepSpeed? [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", ) if use_deepspeed: distributed_type = DistributedType.DEEPSPEED assert is_deepspeed_available(), ( "DeepSpeed is not installed => run `pip3 install deepspeed` or build it from source" )
if distributed_type == DistributedType.DEEPSPEED: use_deepspeed_config = _ask_field( "Do you want to specify a json file to a DeepSpeed config? [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", ) if use_deepspeed_config: deepspeed_config["deepspeed_config_file"] = _ask_field( "Please enter the path to the json DeepSpeed config file: ", str, default="none", ) else: deepspeed_config["zero_stage"] = _ask_options( "What should be your DeepSpeed's ZeRO optimization stage?", [0, 1, 2, 3], int, default=2, )
deepspeed_devices = ["none", "cpu", "nvme"] if deepspeed_config["zero_stage"] >= 2: deepspeed_config["offload_optimizer_device"] = _ask_options( "Where to offload optimizer states?", deepspeed_devices, lambda x: deepspeed_devices[int(x)] ) deepspeed_config["offload_param_device"] = _ask_options( "Where to offload parameters?", deepspeed_devices, lambda x: deepspeed_devices[int(x)] ) if deepspeed_config["offload_param_device"] == "nvme": deepspeed_config["offload_param_nvme_path"] = _ask_field( "Nvme Path to offload parameters?", str, default="/nvme", ) if deepspeed_config["offload_optimizer_device"] == "nvme": deepspeed_config["offload_optimizer_nvme_path"] = _ask_field( "Nvme Path to offload optimizer states?", str, default="/nvme", ) deepspeed_config["gradient_accumulation_steps"] = _ask_field( "How many gradient accumulation steps you're passing in your script? [1]: ", int, default=1, ) use_gradient_clipping = _ask_field( "Do you want to use gradient clipping? [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", ) if use_gradient_clipping: deepspeed_config["gradient_clipping"] = _ask_field( "What is the gradient clipping value? [1.0]: ", float, default=1.0, ) if deepspeed_config["zero_stage"] == 3: deepspeed_config["zero3_save_16bit_model"] = _ask_field( "Do you want to save 16-bit model weights when using ZeRO Stage-3? [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", ) deepspeed_config["zero3_init_flag"] = _ask_field( "Do you want to enable `deepspeed.zero.Init` when using ZeRO Stage-3 for constructing massive models? [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", ) if deepspeed_config["zero3_init_flag"]: if not is_transformers_available(): raise Exception( "When `zero3_init_flag` is set, it requires Transformers to be installed. " "Please run `pip3 install transformers`." ) use_moe = _ask_field( "Do you want to enable Mixture-of-Experts training (MoE)? [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", ) if use_moe: deepspeed_config["deepspeed_moe_layer_cls_names"] = _ask_field( "Specify the comma-separated list of transformers MoE layer class names (case-sensitive), e.g : " " `MixtralSparseMoeBlock`, `Qwen2MoeSparseMoeBlock`, `JetMoEAttention,JetMoEBlock` ... : ", str, )
if num_machines > 1: launcher_query = "Which Type of launcher do you want to use?" deepspeed_config["deepspeed_multinode_launcher"] = _ask_options( launcher_query, DEEPSPEED_MULTINODE_LAUNCHERS, lambda x: DEEPSPEED_MULTINODE_LAUNCHERS[int(x)], )
if deepspeed_config["deepspeed_multinode_launcher"] != DEEPSPEED_MULTINODE_LAUNCHERS[1]: deepspeed_config["deepspeed_hostfile"] = _ask_field( "DeepSpeed configures multi-node compute resources with hostfile. " "Each row is of the format `hostname slots=[num_gpus]`, e.g., `localhost slots=2`; " "for more information please refer official [documentation]" "(https://www.deepspeed.ai/getting-started/#resource-configuration-multi-node). " "Please specify the location of hostfile: ", str, )
is_exclusion_filter = _ask_field( "Do you want to specify exclusion filter string? [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", ) if is_exclusion_filter: deepspeed_config["deepspeed_exclusion_filter"] = _ask_field( "DeepSpeed exclusion filter string: ", str, )
is_inclusion_filter = _ask_field( "Do you want to specify inclusion filter string? [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", ) if is_inclusion_filter: deepspeed_config["deepspeed_inclusion_filter"] = _ask_field( "DeepSpeed inclusion filter string: ", str, )
fsdp_config = {}
if distributed_type in [ DistributedType.MULTI_GPU, DistributedType.MULTI_NPU, DistributedType.MULTI_MLU, DistributedType.MULTI_SDAA, DistributedType.MULTI_MUSA, DistributedType.MULTI_XPU, DistributedType.MULTI_HPU, ]: use_fsdp = _ask_field( "Do you want to use FullyShardedDataParallel? [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", ) if use_fsdp: distributed_type = DistributedType.FSDP if distributed_type == DistributedType.FSDP: fsdp_config["fsdp_version"] = _ask_options( "What should be your FSDP version? [2]: ", [1, 2], lambda x: int(x) + 1, default=1, ) fsdp_version = fsdp_config["fsdp_version"] # extract to a variable to simplify usage later
if fsdp_version == 1: sharding_strategy_query = "What should be your sharding strategy?" fsdp_config["fsdp_reshard_after_forward"] = _ask_options( sharding_strategy_query, FSDP_SHARDING_STRATEGY, lambda x: FSDP_SHARDING_STRATEGY[int(x)], ) else: fsdp_config["fsdp_reshard_after_forward"] = _ask_field( "Do you want to enable resharding after forward? [YES/no]: ", _convert_yes_no_to_bool, default=True, error_message="Please enter yes or no.", )
fsdp_config["fsdp_offload_params"] = _ask_field( "Do you want to offload parameters and gradients to CPU? [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", )
fsdp_wrap_query = "What should be your auto wrap policy?" fsdp_config["fsdp_auto_wrap_policy"] = _ask_options( fsdp_wrap_query, FSDP_AUTO_WRAP_POLICY, lambda x: FSDP_AUTO_WRAP_POLICY[int(x)], ) if fsdp_config["fsdp_auto_wrap_policy"] == FSDP_AUTO_WRAP_POLICY[0]: use_no_split_modules = _ask_field( "Do you want to use the model's `_no_split_modules` to wrap. Only applicable for 🤗 Transformers [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", ) if not use_no_split_modules: fsdp_config["fsdp_transformer_layer_cls_to_wrap"] = _ask_field( "Specify the comma-separated list of transformer layer class names (case-sensitive) to wrap ,e.g, :" "`BertLayer`, `GPTJBlock`, `T5Block`, `BertLayer,BertEmbeddings,BertSelfOutput` ...? : ", str, ) elif fsdp_config["fsdp_auto_wrap_policy"] == FSDP_AUTO_WRAP_POLICY[1]: fsdp_config["fsdp_min_num_params"] = _ask_field( "What should be your FSDP's minimum number of parameters for Default Auto Wrapping Policy? [1e8]: ", int, default=100000000, ) # Removed in FSDP2, ask for user input for FSDP1 if fsdp_version == 1: fsdp_backward_prefetch_query = "What should be your FSDP's backward prefetch policy?" fsdp_config["fsdp_backward_prefetch"] = _ask_options( fsdp_backward_prefetch_query, FSDP_BACKWARD_PREFETCH, lambda x: FSDP_BACKWARD_PREFETCH[int(x)], )
fsdp_state_dict_type_query = "What should be your FSDP's state dict type?" fsdp_config["fsdp_state_dict_type"] = _ask_options( fsdp_state_dict_type_query, FSDP_STATE_DICT_TYPE if fsdp_version == 1 else FSDP2_STATE_DICT_TYPE, lambda x: FSDP_STATE_DICT_TYPE[int(x)] if fsdp_version == 1 else FSDP2_STATE_DICT_TYPE[int(x)], default=0, ) # Not implemented in FSDP2, ask for user input for FSDP1 if fsdp_version == 1: fsdp_config["fsdp_forward_prefetch"] = _ask_field( "Do you want to enable FSDP's forward prefetch policy? [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", ) # Obsolete in FSDP2, ask for user input for FSDP1 if fsdp_version == 1: fsdp_config["fsdp_use_orig_params"] = _ask_field( "Do you want to enable FSDP's `use_orig_params` feature? [YES/no]: ", _convert_yes_no_to_bool, default=True, error_message="Please enter yes or no.", ) fsdp_config["fsdp_cpu_ram_efficient_loading"] = _ask_field( "Do you want to enable CPU RAM efficient model loading? Only applicable for 🤗 Transformers models. [YES/no]: ", _convert_yes_no_to_bool, default=True, error_message="Please enter yes or no.", ) # Obsolete in FSDP2, ask for user input for FSDP1 if fsdp_version == 1: if fsdp_config["fsdp_cpu_ram_efficient_loading"]: fsdp_config["fsdp_sync_module_states"] = True else: fsdp_config["fsdp_sync_module_states"] = _ask_field( "Do you want each individually wrapped FSDP unit to broadcast module parameters from rank 0 at the start? [YES/no]: ", _convert_yes_no_to_bool, default=True, error_message="Please enter yes or no.", ) fsdp_config["fsdp_activation_checkpointing"] = _ask_field( "Do you want to enable FSDP activation checkpointing? [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", )
megatron_lm_config = {} if distributed_type in [DistributedType.MULTI_GPU]: use_megatron_lm = _ask_field( "Do you want to use Megatron-LM ? [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", ) if use_megatron_lm: distributed_type = DistributedType.MEGATRON_LM if distributed_type == DistributedType.MEGATRON_LM: prefix = "megatron_lm_" megatron_lm_config[prefix + "tp_degree"] = _ask_field( "What is the Tensor Parallelism degree/size? [1]:", int, default=1, error_message="Please enter an integer.", ) if megatron_lm_config[prefix + "tp_degree"] > 1: megatron_lm_config[prefix + "sequence_parallelism"] = _ask_field( "Do you want to enable Sequence Parallelism? [YES/no]: ", _convert_yes_no_to_bool, default=True, error_message="Please enter yes or no.", )
megatron_lm_config[prefix + "pp_degree"] = _ask_field( "What is the Pipeline Parallelism degree/size? [1]:", int, default=1, error_message="Please enter an integer.", ) if megatron_lm_config[prefix + "pp_degree"] > 1: megatron_lm_config[prefix + "num_micro_batches"] = _ask_field( "What is the number of micro-batches? [1]:", int, default=1, error_message="Please enter an integer.", )
megatron_lm_config[prefix + "recompute_activations"] = _ask_field( "Do you want to enable selective activation recomputation? [YES/no]: ", _convert_yes_no_to_bool, default=True, error_message="Please enter yes or no.", )
megatron_lm_config[prefix + "use_distributed_optimizer"] = _ask_field( "Do you want to use distributed optimizer " "which shards optimizer state and gradients across data parallel ranks? [YES/no]: ", _convert_yes_no_to_bool, default=True, error_message="Please enter yes or no.", )
megatron_lm_config[prefix + "gradient_clipping"] = _ask_field( "What is the gradient clipping value based on global L2 Norm (0 to disable)? [1.0]: ", float, default=1.0, ) # TPU specific defaults tpu_commands = None tpu_command_file = None tpu_downcast_bf16 = "no" tpu_env = [] tpu_name = None tpu_vm = None tpu_zone = None tpu_use_sudo = False tpu_use_cluster = False
if distributed_type in [ DistributedType.MULTI_CPU, DistributedType.MULTI_XPU, DistributedType.MULTI_HPU, DistributedType.MULTI_GPU, DistributedType.MULTI_MLU, DistributedType.MULTI_SDAA, DistributedType.MULTI_MUSA, DistributedType.MULTI_NPU, DistributedType.XLA, ]: machine_type = str(distributed_type).split(".")[1].replace("MULTI_", "") if machine_type == "TPU": machine_type += " cores" elif machine_type == "CPU": machine_type = "processes" else: machine_type += "(s)" num_processes = _ask_field( f"How many {machine_type} should be used for distributed training? [1]:", int, default=1, error_message="Please enter an integer.", ) elif distributed_type in [DistributedType.FSDP, DistributedType.DEEPSPEED, DistributedType.MEGATRON_LM]: num_processes = _ask_field( "How many GPU(s) should be used for distributed training? [1]:", int, default=1, error_message="Please enter an integer.", ) else: num_processes = 1
if (distributed_type == DistributedType.MULTI_GPU) and (num_machines == 1) and (num_processes == 1): raise ValueError( f"Specified distributed type {distributed_type} but only using 1 GPU on a single machine. Please select `No distributed training` for the type of machine you are using." )
if ( distributed_type in [ DistributedType.MULTI_GPU, DistributedType.MULTI_MLU, DistributedType.MULTI_SDAA, DistributedType.MULTI_MUSA, DistributedType.MULTI_NPU, DistributedType.MULTI_XPU, DistributedType.MULTI_HPU, DistributedType.NO, ] and not use_cpu and not use_mps ): if is_npu_available(): machine_type = "NPU(s)" elif is_mlu_available(): machine_type = "MLU(s)" elif is_sdaa_available(): machine_type = "SDAA(s)" elif is_musa_available(): machine_type = "MUSA(s)" elif is_xpu_available(): machine_type = "XPU(s)" elif is_hpu_available(): machine_type = "HPU(s)" else: machine_type = "GPU(s)" gpu_ids = _ask_field( f"What {machine_type} (by id) should be used for training on this machine as a comma-separated list? [all]:", default="all", )
# CPU affinity is only supported on NVIDIA hardware for now enable_cpu_affinity = False if distributed_type in (DistributedType.NO, DistributedType.MULTI_GPU) and not use_cpu and not use_mps: enable_cpu_affinity = _ask_field( "Would you like to enable numa efficiency? (Currently only supported on NVIDIA hardware). [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", )
fp8_config = None if distributed_type == DistributedType.XLA: mixed_precision = "no" main_training_function = _ask_field( "What is the name of the function in your script that should be launched in all parallel scripts? [main]: ", default="main", ) tpu_use_cluster = _ask_field( "Are you using a TPU cluster? [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", ) if tpu_use_cluster: tpu_name = _ask_field( "What is the name of your TPU cluster? ", default=None, error_message="Please enter the name of your TPU cluster.", ) tpu_zone = _ask_field( "What is the zone of your TPU cluster? ", default=None, error_message="Please enter the zone of your TPU cluster.", ) tpu_use_sudo = _ask_field( "To run a python script in a TPU pod, should `sudo` be used? [yes/NO]: ", default=False, error_message="Please enter yes or no.", ) run_commands = _ask_field( "Do you have code you wish to run on startup in each pod? [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", ) if run_commands: use_command_file = _ask_field( "Is this code located in a bash script? [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", ) if use_command_file: tpu_command_file = _ask_field( "What is the path to your bash script? ", default=None, error_message="Please enter the path to your bash script.", ) tpu_command_file = os.path.abspath(tpu_command_file) else: print("Please enter each command separately you wish to run on startup in each pod.") tpu_commands = [] another_command = True while another_command: tpu_commands.append( _ask_field( "Please enter a single command to be ran ", default=None, error_message="Please enter the commands you wish to run on startup in each pod as a single string.", ) ) another_command = _ask_field( "Do you wish to add another command? [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", ) tpu_vm = _ask_field( "If not using an instance group, what are the names of the Compute VM instances to be used, separated by a comma: ", default="", ).split(",") tpu_env = _ask_field( "What environment variables do you wish to set in each pod, separated by a comma: ", default="", ).split(",")
else: main_training_function = "main" if distributed_type == DistributedType.DEEPSPEED and use_deepspeed_config: mixed_precision = None else: mixed_precision = _ask_options( "Do you wish to use mixed precision?", ["no", "fp16", "bf16", "fp8"], _convert_mixed_precision, ) if mixed_precision == "fp8": if not is_fp8_available(): raise ValueError("FP8 (either Transformer Engine or MSAMP) is not installed on this machine.") fp8_config = {} fp8_config["backend"] = _ask_options( "Which FP8 backend do you want to use?", ["te", "msamp"], _convert_fp8_backend, ) if fp8_config["backend"] == "TE": if not is_transformer_engine_available(): raise ValueError("TransformersEngine was selected, but it is not installed on this machine.") fp8_config["use_autocast_during_eval"] = _ask_field( "Do you want to use FP8 autocast during eval mode? Generally better metrics are found when this is disabled [yes/NO]: ", _convert_yes_no_to_bool, default=False, ) fp8_config["margin"] = _ask_field( "What margin should be used for gradient scaling? [0]: ", int, default=0, ) fp8_config["interval"] = _ask_field( "What interval should be used for for how often the scaling factor is recomputed? [1]: ", int, default=1, ) fp8_config["fp8_format"] = _ask_options( "Which weight format should be used?", ["HYBRID", "E4M3"], lambda x: "HYBRID" if x == 0 else "E4M3", default=0, ) fp8_config["amax_history_length"] = _ask_field( "What length of history should be used for the amax scaling factor computation? [1024]: ", int, default=1024, ) fp8_config["amax_compute_algorithm"] = _ask_options( "Which algorithm should be used for the amax scaling factor computation?", ["max", "most_recent"], lambda x: "max" if x == 0 else "most_recent", default=0, ) fp8_config["override_linear_precision"] = _ask_field( "Do you want to to execute `fprop`, `dgrad`, and `wgrad` GEMMS in higher precision? [yes/NO]: ", _convert_yes_no_to_bool, default=False, ) if fp8_config["override_linear_precision"]: fprop = _ask_field( "Should `fprop` be executed in higher precision? [yes/NO]: ", _convert_yes_no_to_bool, default=False, ) dgrad = _ask_field( "Should `dgrad` be executed in higher precision? [yes/NO]: ", _convert_yes_no_to_bool, default=False, ) wgrad = _ask_field( "Should `wgrad` be executed in higher precision? [yes/NO]: ", _convert_yes_no_to_bool, default=False, ) fp8_config["override_linear_precision"] = (fprop, dgrad, wgrad) else: fp8_config["override_linear_precision"] = (False, False, False)
elif fp8_config["backend"] == "MSAMP": if not is_msamp_available(): raise ValueError("MSAMP was selected, but it is not installed on this machine.") fp8_config["optimization_level"] = _ask_options( "Which optimization level should be used?", ["O1", "O2"], lambda x: "O1" if x == 0 else "O2", default=1, )
if use_dynamo and mixed_precision == "no" and not use_cpu: print( "Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts." )
if distributed_type == DistributedType.XLA and mixed_precision == "bf16": tpu_downcast_bf16 = _ask_field( "Should `torch.float` be cast as `bfloat16` and `torch.double` remain `float32` on TPUs?", default="no" )
return ClusterConfig( compute_environment=ComputeEnvironment.LOCAL_MACHINE, distributed_type=distributed_type, num_processes=num_processes, gpu_ids=gpu_ids, mixed_precision=mixed_precision, downcast_bf16=tpu_downcast_bf16, machine_rank=machine_rank, num_machines=num_machines, main_process_ip=main_process_ip, main_process_port=main_process_port, main_training_function=main_training_function, fp8_config=fp8_config, deepspeed_config=deepspeed_config, fsdp_config=fsdp_config, megatron_lm_config=megatron_lm_config, ipex_config=ipex_config, mpirun_config=mpirun_config, use_cpu=use_cpu, rdzv_backend=rdzv_backend, same_network=same_network, commands=tpu_commands, command_file=tpu_command_file, tpu_env=tpu_env, tpu_name=tpu_name, tpu_vm=tpu_vm, tpu_zone=tpu_zone, tpu_use_sudo=tpu_use_sudo, tpu_use_cluster=tpu_use_cluster, dynamo_config=dynamo_config, debug=debug, enable_cpu_affinity=enable_cpu_affinity, )1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889#!/usr/bin/env python
# Copyright 2021 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import argparseimport os
from accelerate.utils import ComputeEnvironment
from .cluster import get_cluster_inputfrom .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401from .sagemaker import get_sagemaker_input
description = "Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine"
def get_user_input(): compute_environment = _ask_options( "In which compute environment are you running?", ["This machine", "AWS (Amazon SageMaker)"], _convert_compute_environment, ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: config = get_sagemaker_input() else: config = get_cluster_input() return config
def config_command_parser(subparsers=None): if subparsers is not None: parser = subparsers.add_parser("config", description=description) else: parser = argparse.ArgumentParser("Accelerate config command", description=description)
parser.add_argument( "--config_file", default=None, help=( "The path to use to store the config file. Will default to a file named default_config.yaml in the cache " "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have " "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed " "with 'huggingface'." ), )
if subparsers is not None: parser.set_defaults(func=config_command) return parser
def config_command(args): config = get_user_input() if args.config_file is not None: config_file = args.config_file else: if not os.path.isdir(cache_dir): os.makedirs(cache_dir) config_file = default_yaml_config_file
if config_file.endswith(".json"): config.to_json_file(config_file) else: config.to_yaml_file(config_file) print(f"accelerate configuration saved at {config_file}")
def main(): parser = config_command_parser() args = parser.parse_args() config_command(args)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252#!/usr/bin/env python
# Copyright 2021 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import jsonimport osfrom dataclasses import dataclassfrom enum import Enumfrom typing import Optional, Union
import yaml
from ...utils import ComputeEnvironment, DistributedType, SageMakerDistributedTypefrom ...utils.constants import SAGEMAKER_PYTHON_VERSION, SAGEMAKER_PYTORCH_VERSION, SAGEMAKER_TRANSFORMERS_VERSION
hf_cache_home = os.path.expanduser( os.environ.get("HF_HOME", os.path.join(os.environ.get("XDG_CACHE_HOME", "~/.cache"), "huggingface")))cache_dir = os.path.join(hf_cache_home, "accelerate")default_json_config_file = os.path.join(cache_dir, "default_config.yaml")default_yaml_config_file = os.path.join(cache_dir, "default_config.yaml")
# For backward compatibility: the default config is the json one if it's the only existing file.if os.path.isfile(default_yaml_config_file) or not os.path.isfile(default_json_config_file): default_config_file = default_yaml_config_fileelse: default_config_file = default_json_config_file
def load_config_from_file(config_file): if config_file is not None: if not os.path.isfile(config_file): raise FileNotFoundError( f"The passed configuration file `{config_file}` does not exist. " "Please pass an existing file to `accelerate launch`, or use the default one " "created through `accelerate config` and run `accelerate launch` " "without the `--config_file` argument." ) else: config_file = default_config_file with open(config_file, encoding="utf-8") as f: if config_file.endswith(".json"): if ( json.load(f).get("compute_environment", ComputeEnvironment.LOCAL_MACHINE) == ComputeEnvironment.LOCAL_MACHINE ): config_class = ClusterConfig else: config_class = SageMakerConfig return config_class.from_json_file(json_file=config_file) else: if ( yaml.safe_load(f).get("compute_environment", ComputeEnvironment.LOCAL_MACHINE) == ComputeEnvironment.LOCAL_MACHINE ): config_class = ClusterConfig else: config_class = SageMakerConfig return config_class.from_yaml_file(yaml_file=config_file)
@dataclassclass BaseConfig: compute_environment: ComputeEnvironment distributed_type: Union[DistributedType, SageMakerDistributedType] mixed_precision: str use_cpu: bool debug: bool
def to_dict(self): result = self.__dict__ # For serialization, it's best to convert Enums to strings (or their underlying value type).
def _convert_enums(value): if isinstance(value, Enum): return value.value if isinstance(value, dict): if not bool(value): return None for key1, value1 in value.items(): value[key1] = _convert_enums(value1) return value
for key, value in result.items(): result[key] = _convert_enums(value) result = {k: v for k, v in result.items() if v is not None} return result
@staticmethod def process_config(config_dict): """ Processes `config_dict` and sets default values for any missing keys """ if "compute_environment" not in config_dict: config_dict["compute_environment"] = ComputeEnvironment.LOCAL_MACHINE if "distributed_type" not in config_dict: raise ValueError("A `distributed_type` must be specified in the config file.") if "num_processes" not in config_dict and config_dict["distributed_type"] == DistributedType.NO: config_dict["num_processes"] = 1 if "mixed_precision" not in config_dict: config_dict["mixed_precision"] = "fp16" if ("fp16" in config_dict and config_dict["fp16"]) else None if "fp16" in config_dict: # Convert the config to the new format. del config_dict["fp16"] if "dynamo_backend" in config_dict: # Convert the config to the new format. dynamo_backend = config_dict.pop("dynamo_backend") config_dict["dynamo_config"] = {} if dynamo_backend == "NO" else {"dynamo_backend": dynamo_backend} if "use_cpu" not in config_dict: config_dict["use_cpu"] = False if "debug" not in config_dict: config_dict["debug"] = False if "enable_cpu_affinity" not in config_dict: config_dict["enable_cpu_affinity"] = False return config_dict
@classmethod def from_json_file(cls, json_file=None): json_file = default_json_config_file if json_file is None else json_file with open(json_file, encoding="utf-8") as f: config_dict = json.load(f) config_dict = cls.process_config(config_dict) extra_keys = sorted(set(config_dict.keys()) - set(cls.__dataclass_fields__.keys())) if len(extra_keys) > 0: raise ValueError( f"The config file at {json_file} had unknown keys ({extra_keys}), please try upgrading your `accelerate`" " version or fix (and potentially remove) these keys from your config file." )
return cls(**config_dict)
def to_json_file(self, json_file): with open(json_file, "w", encoding="utf-8") as f: content = json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n" f.write(content)
@classmethod def from_yaml_file(cls, yaml_file=None): yaml_file = default_yaml_config_file if yaml_file is None else yaml_file with open(yaml_file, encoding="utf-8") as f: config_dict = yaml.safe_load(f) config_dict = cls.process_config(config_dict) extra_keys = sorted(set(config_dict.keys()) - set(cls.__dataclass_fields__.keys())) if len(extra_keys) > 0: raise ValueError( f"The config file at {yaml_file} had unknown keys ({extra_keys}), please try upgrading your `accelerate`" " version or fix (and potentially remove) these keys from your config file." ) return cls(**config_dict)
def to_yaml_file(self, yaml_file): with open(yaml_file, "w", encoding="utf-8") as f: yaml.safe_dump(self.to_dict(), f)
def __post_init__(self): if isinstance(self.compute_environment, str): self.compute_environment = ComputeEnvironment(self.compute_environment) if isinstance(self.distributed_type, str): if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: self.distributed_type = SageMakerDistributedType(self.distributed_type) else: self.distributed_type = DistributedType(self.distributed_type) if getattr(self, "dynamo_config", None) is None: self.dynamo_config = {}
@dataclassclass ClusterConfig(BaseConfig): num_processes: int = -1 # For instance if we use SLURM and the user manually passes it in machine_rank: int = 0 num_machines: int = 1 gpu_ids: Optional[str] = None main_process_ip: Optional[str] = None main_process_port: Optional[int] = None rdzv_backend: Optional[str] = "static" same_network: Optional[bool] = False main_training_function: str = "main" enable_cpu_affinity: bool = False
# args for FP8 training fp8_config: dict = None # args for deepspeed_plugin deepspeed_config: dict = None # args for fsdp fsdp_config: dict = None # args for megatron_lm megatron_lm_config: dict = None # args for ipex ipex_config: dict = None # args for mpirun mpirun_config: dict = None # args for TPU downcast_bf16: bool = False
# args for TPU pods tpu_name: str = None tpu_zone: str = None tpu_use_cluster: bool = False tpu_use_sudo: bool = False command_file: str = None commands: list[str] = None tpu_vm: list[str] = None tpu_env: list[str] = None
# args for dynamo dynamo_config: dict = None
def __post_init__(self): if self.deepspeed_config is None: self.deepspeed_config = {} if self.fsdp_config is None: self.fsdp_config = {} if self.megatron_lm_config is None: self.megatron_lm_config = {} if self.ipex_config is None: self.ipex_config = {} if self.mpirun_config is None: self.mpirun_config = {} if self.fp8_config is None: self.fp8_config = {} return super().__post_init__()
@dataclassclass SageMakerConfig(BaseConfig): ec2_instance_type: str iam_role_name: str image_uri: Optional[str] = None profile: Optional[str] = None region: str = "us-east-1" num_machines: int = 1 gpu_ids: str = "all" base_job_name: str = f"accelerate-sagemaker-{num_machines}" pytorch_version: str = SAGEMAKER_PYTORCH_VERSION transformers_version: str = SAGEMAKER_TRANSFORMERS_VERSION py_version: str = SAGEMAKER_PYTHON_VERSION sagemaker_inputs_file: str = None sagemaker_metrics_file: str = None additional_args: dict = None dynamo_config: dict = None enable_cpu_affinity: bool = False123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122#!/usr/bin/env python
# Copyright 2021 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import argparse
from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, FP8BackendType, PrecisionType, SageMakerDistributedType,)from ..menu import BulletMenu
DYNAMO_BACKENDS = [ "EAGER", "AOT_EAGER", "INDUCTOR", "AOT_TS_NVFUSER", "NVPRIMS_NVFUSER", "CUDAGRAPHS", "OFI", "FX2TRT", "ONNXRT", "TENSORRT", "AOT_TORCHXLA_TRACE_ONCE", "TORHCHXLA_TRACE_ONCE", "IPEX", "TVM",]
def _ask_field(input_text, convert_value=None, default=None, error_message=None): ask_again = True while ask_again: result = input(input_text) try: if default is not None and len(result) == 0: return default return convert_value(result) if convert_value is not None else result except Exception: if error_message is not None: print(error_message)
def _ask_options(input_text, options=[], convert_value=None, default=0): menu = BulletMenu(input_text, options) result = menu.run(default_choice=default) return convert_value(result) if convert_value is not None else result
def _convert_compute_environment(value): value = int(value) return ComputeEnvironment(["LOCAL_MACHINE", "AMAZON_SAGEMAKER"][value])
def _convert_distributed_mode(value): value = int(value) return DistributedType( [ "NO", "MULTI_CPU", "MULTI_XPU", "MULTI_HPU", "MULTI_GPU", "MULTI_NPU", "MULTI_MLU", "MULTI_SDAA", "MULTI_MUSA", "XLA", ][value] )
def _convert_dynamo_backend(value): value = int(value) return DynamoBackend(DYNAMO_BACKENDS[value]).value
def _convert_mixed_precision(value): value = int(value) return PrecisionType(["no", "fp16", "bf16", "fp8"][value])
def _convert_sagemaker_distributed_mode(value): value = int(value) return SageMakerDistributedType(["NO", "DATA_PARALLEL", "MODEL_PARALLEL"][value])
def _convert_fp8_backend(value): value = int(value) return FP8BackendType(["TE", "MSAMP"][value])
def _convert_yes_no_to_bool(value): return {"yes": True, "no": False}[value.lower()]
class SubcommandHelpFormatter(argparse.RawDescriptionHelpFormatter): """ A custom formatter that will remove the usage line from the help message for subcommands. """
def _format_usage(self, usage, actions, groups, prefix): usage = super()._format_usage(usage, actions, groups, prefix) usage = usage.replace("<command> [<args>] ", "") return usage123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163#!/usr/bin/env python
# Copyright 2021 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
from pathlib import Path
import torch
from ...utils import ( is_hpu_available, is_mlu_available, is_musa_available, is_npu_available, is_sdaa_available, is_xpu_available,)from .config_args import ClusterConfig, default_json_config_filefrom .config_utils import SubcommandHelpFormatter
description = "Create a default config file for Accelerate with only a few flags set."
def write_basic_config(mixed_precision="no", save_location: str = default_json_config_file): """ Creates and saves a basic cluster config to be used on a local machine with potentially multiple GPUs. Will also set CPU if it is a CPU-only machine.
Args: mixed_precision (`str`, *optional*, defaults to "no"): Mixed Precision to use. Should be one of "no", "fp16", or "bf16" save_location (`str`, *optional*, defaults to `default_json_config_file`): Optional custom save location. Should be passed to `--config_file` when using `accelerate launch`. Default location is inside the huggingface cache folder (`~/.cache/huggingface`) but can be overridden by setting the `HF_HOME` environmental variable, followed by `accelerate/default_config.yaml`. """ path = Path(save_location) path.parent.mkdir(parents=True, exist_ok=True) if path.exists(): print( f"Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`." ) return False mixed_precision = mixed_precision.lower() if mixed_precision not in ["no", "fp16", "bf16", "fp8"]: raise ValueError( f"`mixed_precision` should be one of 'no', 'fp16', 'bf16', or 'fp8'. Received {mixed_precision}" ) config = { "compute_environment": "LOCAL_MACHINE", "mixed_precision": mixed_precision, } if is_mlu_available(): num_mlus = torch.mlu.device_count() config["num_processes"] = num_mlus config["use_cpu"] = False if num_mlus > 1: config["distributed_type"] = "MULTI_MLU" else: config["distributed_type"] = "NO" if is_sdaa_available(): num_sdaas = torch.sdaa.device_count() config["num_processes"] = num_sdaas config["use_cpu"] = False if num_sdaas > 1: config["distributed_type"] = "MULTI_SDAA" else: config["distributed_type"] = "NO" elif is_musa_available(): num_musas = torch.musa.device_count() config["num_processes"] = num_musas config["use_cpu"] = False if num_musas > 1: config["distributed_type"] = "MULTI_MUSA" else: config["distributed_type"] = "NO" elif is_hpu_available(): num_hpus = torch.hpu.device_count() config["num_processes"] = num_hpus config["use_cpu"] = False if num_hpus > 1: config["distributed_type"] = "MULTI_HPU" else: config["distributed_type"] = "NO" elif torch.cuda.is_available(): num_gpus = torch.cuda.device_count() config["num_processes"] = num_gpus config["use_cpu"] = False if num_gpus > 1: config["distributed_type"] = "MULTI_GPU" else: config["distributed_type"] = "NO" elif is_xpu_available(): num_xpus = torch.xpu.device_count() config["num_processes"] = num_xpus config["use_cpu"] = False if num_xpus > 1: config["distributed_type"] = "MULTI_XPU" else: config["distributed_type"] = "NO" elif is_npu_available(): num_npus = torch.npu.device_count() config["num_processes"] = num_npus config["use_cpu"] = False if num_npus > 1: config["distributed_type"] = "MULTI_NPU" else: config["distributed_type"] = "NO" else: num_xpus = 0 config["use_cpu"] = True config["num_processes"] = 1 config["distributed_type"] = "NO" config["debug"] = False config["enable_cpu_affinity"] = False config = ClusterConfig(**config) config.to_json_file(path) return path
def default_command_parser(parser, parents): parser = parser.add_parser("default", parents=parents, help=description, formatter_class=SubcommandHelpFormatter) parser.add_argument( "--config_file", default=default_json_config_file, help=( "The path to use to store the config file. Will default to a file named default_config.yaml in the cache " "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have " "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed " "with 'huggingface'." ), dest="save_location", )
parser.add_argument( "--mixed_precision", choices=["no", "fp16", "bf16"], type=str, help="Whether or not to use mixed precision training. " "Choose between FP16 and BF16 (bfloat16) training. " "BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.", default="no", ) parser.set_defaults(func=default_config_command) return parser
def default_config_command(args): config_file = write_basic_config(args.mixed_precision, args.save_location) if config_file: print(f"accelerate configuration saved at {config_file}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274#!/usr/bin/env python
# Copyright 2021 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.import jsonimport os
from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODESfrom ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedTypefrom ...utils.imports import is_boto3_availablefrom .config_args import SageMakerConfigfrom .config_utils import ( DYNAMO_BACKENDS, _ask_field, _ask_options, _convert_dynamo_backend, _convert_mixed_precision, _convert_sagemaker_distributed_mode, _convert_yes_no_to_bool,)
if is_boto3_available(): import boto3 # noqa: F401
def _create_iam_role_for_sagemaker(role_name): iam_client = boto3.client("iam")
sagemaker_trust_policy = { "Version": "2012-10-17", "Statement": [ {"Effect": "Allow", "Principal": {"Service": "sagemaker.amazonaws.com"}, "Action": "sts:AssumeRole"} ], } try: # create the role, associated with the chosen trust policy iam_client.create_role( RoleName=role_name, AssumeRolePolicyDocument=json.dumps(sagemaker_trust_policy, indent=2) ) policy_document = { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "sagemaker:*", "ecr:GetDownloadUrlForLayer", "ecr:BatchGetImage", "ecr:BatchCheckLayerAvailability", "ecr:GetAuthorizationToken", "cloudwatch:PutMetricData", "cloudwatch:GetMetricData", "cloudwatch:GetMetricStatistics", "cloudwatch:ListMetrics", "logs:CreateLogGroup", "logs:CreateLogStream", "logs:DescribeLogStreams", "logs:PutLogEvents", "logs:GetLogEvents", "s3:CreateBucket", "s3:ListBucket", "s3:GetBucketLocation", "s3:GetObject", "s3:PutObject", ], "Resource": "*", } ], } # attach policy to role iam_client.put_role_policy( RoleName=role_name, PolicyName=f"{role_name}_policy_permission", PolicyDocument=json.dumps(policy_document, indent=2), ) except iam_client.exceptions.EntityAlreadyExistsException: print(f"role {role_name} already exists. Using existing one")
def _get_iam_role_arn(role_name): iam_client = boto3.client("iam") return iam_client.get_role(RoleName=role_name)["Role"]["Arn"]
def get_sagemaker_input(): credentials_configuration = _ask_options( "How do you want to authorize?", ["AWS Profile", "Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) "], int, ) aws_profile = None if credentials_configuration == 0: aws_profile = _ask_field("Enter your AWS Profile name: [default] ", default="default") os.environ["AWS_PROFILE"] = aws_profile else: print( "Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with," "`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`" ) aws_access_key_id = _ask_field("AWS Access Key ID: ") os.environ["AWS_ACCESS_KEY_ID"] = aws_access_key_id
aws_secret_access_key = _ask_field("AWS Secret Access Key: ") os.environ["AWS_SECRET_ACCESS_KEY"] = aws_secret_access_key
aws_region = _ask_field("Enter your AWS Region: [us-east-1]", default="us-east-1") os.environ["AWS_DEFAULT_REGION"] = aws_region
role_management = _ask_options( "Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?", ["Provide IAM Role name", "Create new IAM role using credentials"], int, ) if role_management == 0: iam_role_name = _ask_field("Enter your IAM role name: ") else: iam_role_name = "accelerate_sagemaker_execution_role" print(f'Accelerate will create an iam role "{iam_role_name}" using the provided credentials') _create_iam_role_for_sagemaker(iam_role_name)
is_custom_docker_image = _ask_field( "Do you want to use custom Docker image? [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", ) docker_image = None if is_custom_docker_image: docker_image = _ask_field("Enter your Docker image: ", lambda x: str(x).lower())
is_sagemaker_inputs_enabled = _ask_field( "Do you want to provide SageMaker input channels with data locations? [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", ) sagemaker_inputs_file = None if is_sagemaker_inputs_enabled: sagemaker_inputs_file = _ask_field( "Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): ", lambda x: str(x).lower(), )
is_sagemaker_metrics_enabled = _ask_field( "Do you want to enable SageMaker metrics? [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", ) sagemaker_metrics_file = None if is_sagemaker_metrics_enabled: sagemaker_metrics_file = _ask_field( "Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): ", lambda x: str(x).lower(), )
distributed_type = _ask_options( "What is the distributed mode?", ["No distributed training", "Data parallelism"], _convert_sagemaker_distributed_mode, ) dynamo_config = {} use_dynamo = _ask_field( "Do you wish to optimize your script with torch dynamo?[yes/NO]:", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", ) if use_dynamo: prefix = "dynamo_" dynamo_config[prefix + "backend"] = _ask_options( "Which dynamo backend would you like to use?", [x.lower() for x in DYNAMO_BACKENDS], _convert_dynamo_backend, default=2, ) use_custom_options = _ask_field( "Do you want to customize the defaults sent to torch.compile? [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", )
if use_custom_options: dynamo_config[prefix + "mode"] = _ask_options( "Which mode do you want to use?", TORCH_DYNAMO_MODES, lambda x: TORCH_DYNAMO_MODES[int(x)], default="default", ) dynamo_config[prefix + "use_fullgraph"] = _ask_field( "Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", ) dynamo_config[prefix + "use_dynamic"] = _ask_field( "Do you want to enable dynamic shape tracing? [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", ) dynamo_config[prefix + "use_regional_compilation"] = _ask_field( "Do you want to enable regional compilation? [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", )
ec2_instance_query = "Which EC2 instance type you want to use for your training?" if distributed_type != SageMakerDistributedType.NO: ec2_instance_type = _ask_options( ec2_instance_query, SAGEMAKER_PARALLEL_EC2_INSTANCES, lambda x: SAGEMAKER_PARALLEL_EC2_INSTANCES[int(x)] ) else: ec2_instance_query += "? [ml.p3.2xlarge]:" ec2_instance_type = _ask_field(ec2_instance_query, lambda x: str(x).lower(), default="ml.p3.2xlarge")
debug = False if distributed_type != SageMakerDistributedType.NO: debug = _ask_field( "Should distributed operations be checked while running for errors? This can avoid timeout issues but will be slower. [yes/NO]: ", _convert_yes_no_to_bool, default=False, error_message="Please enter yes or no.", )
num_machines = 1 if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL): num_machines = _ask_field( "How many machines do you want use? [1]: ", int, default=1, )
mixed_precision = _ask_options( "Do you wish to use FP16 or BF16 (mixed precision)?", ["no", "fp16", "bf16", "fp8"], _convert_mixed_precision, )
if use_dynamo and mixed_precision == "no": print( "Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts." )
return SageMakerConfig( image_uri=docker_image, compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER, distributed_type=distributed_type, use_cpu=False, dynamo_config=dynamo_config, ec2_instance_type=ec2_instance_type, profile=aws_profile, region=aws_region, iam_role_name=iam_role_name, mixed_precision=mixed_precision, num_machines=num_machines, sagemaker_inputs_file=sagemaker_inputs_file, sagemaker_metrics_file=sagemaker_metrics_file, debug=debug, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263#!/usr/bin/env python
# Copyright 2022 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
from pathlib import Path
from .config_args import default_config_file, load_config_from_filefrom .config_utils import SubcommandHelpFormatter
description = "Update an existing config file with the latest defaults while maintaining the old configuration."
def update_config(args): """ Update an existing config file with the latest defaults while maintaining the old configuration. """ config_file = args.config_file if config_file is None and Path(default_config_file).exists(): config_file = default_config_file elif not Path(config_file).exists(): raise ValueError(f"The passed config file located at {config_file} doesn't exist.") config = load_config_from_file(config_file)
if config_file.endswith(".json"): config.to_json_file(config_file) else: config.to_yaml_file(config_file) return config_file
def update_command_parser(parser, parents): parser = parser.add_parser("update", parents=parents, help=description, formatter_class=SubcommandHelpFormatter) parser.add_argument( "--config_file", default=None, help=( "The path to the config file to update. Will default to a file named default_config.yaml in the cache " "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have " "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed " "with 'huggingface'." ), )
parser.set_defaults(func=update_config_command) return parser
def update_config_command(args): config_file = update_config(args) print(f"Sucessfully updated the configuration file at {config_file}.")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131#!/usr/bin/env python
# Copyright 2022 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import argparseimport osimport platformimport subprocess
import numpy as npimport psutilimport torch
from accelerate import __version__ as versionfrom accelerate.commands.config import default_config_file, load_config_from_file
from ..utils import is_mlu_available, is_musa_available, is_npu_available, is_sdaa_available, is_xpu_available
def env_command_parser(subparsers=None): if subparsers is not None: parser = subparsers.add_parser("env") else: parser = argparse.ArgumentParser("Accelerate env command")
parser.add_argument( "--config_file", default=None, help="The config file to use for the default values in the launching script." )
if subparsers is not None: parser.set_defaults(func=env_command) return parser
def env_command(args): pt_version = torch.__version__ pt_cuda_available = torch.cuda.is_available() pt_xpu_available = is_xpu_available() pt_mlu_available = is_mlu_available() pt_sdaa_available = is_sdaa_available() pt_musa_available = is_musa_available() pt_npu_available = is_npu_available()
accelerator = "N/A" if pt_cuda_available: accelerator = "CUDA" elif pt_xpu_available: accelerator = "XPU" elif pt_mlu_available: accelerator = "MLU" elif pt_sdaa_available: accelerator = "SDAA" elif pt_musa_available: accelerator = "MUSA" elif pt_npu_available: accelerator = "NPU"
accelerate_config = "Not found" # Get the default from the config file. if args.config_file is not None or os.path.isfile(default_config_file): accelerate_config = load_config_from_file(args.config_file).to_dict()
# if we can run which, get it command = None bash_location = "Not found" if os.name == "nt": command = ["where", "accelerate"] elif os.name == "posix": command = ["which", "accelerate"] if command is not None: bash_location = subprocess.check_output(command, text=True, stderr=subprocess.STDOUT).strip() info = { "`Accelerate` version": version, "Platform": platform.platform(), "`accelerate` bash location": bash_location, "Python version": platform.python_version(), "Numpy version": np.__version__, "PyTorch version": f"{pt_version}", "PyTorch accelerator": accelerator, "System RAM": f"{psutil.virtual_memory().total / 1024**3:.2f} GB", } if pt_cuda_available: info["GPU type"] = torch.cuda.get_device_name() elif pt_xpu_available: info["XPU type"] = torch.xpu.get_device_name() elif pt_mlu_available: info["MLU type"] = torch.mlu.get_device_name() elif pt_sdaa_available: info["SDAA type"] = torch.sdaa.get_device_name() elif pt_musa_available: info["MUSA type"] = torch.musa.get_device_name() elif pt_npu_available: info["CANN version"] = torch.version.cann
print("\nCopy-and-paste the text below in your GitHub issue\n") print("\n".join([f"- {prop}: {val}" for prop, val in info.items()]))
print("- `Accelerate` default config:" if args.config_file is None else "- `Accelerate` config passed:") accelerate_config_str = ( "\n".join([f"\t- {prop}: {val}" for prop, val in accelerate_config.items()]) if isinstance(accelerate_config, dict) else f"\t{accelerate_config}" ) print(accelerate_config_str)
info["`Accelerate` configs"] = accelerate_config
return info
def main() -> int: parser = env_command_parser() args = parser.parse_args() env_command(args) return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312#!/usr/bin/env python
# Copyright 2023 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.import torchfrom huggingface_hub import model_infofrom huggingface_hub.utils import GatedRepoError, RepositoryNotFoundError
from accelerate import init_empty_weightsfrom accelerate.commands.utils import CustomArgumentParserfrom accelerate.utils import ( calculate_maximum_sizes, convert_bytes, is_timm_available, is_transformers_available,)
if is_transformers_available(): import transformers from transformers import AutoConfig, AutoModel
if is_timm_available(): import timm
def verify_on_hub(repo: str, token: str = None): "Verifies that the model is on the hub and returns the model info." try: return model_info(repo, token=token) except (OSError, GatedRepoError): return "gated" except RepositoryNotFoundError: return "repo"
def check_has_model(error): """ Checks what library spawned `error` when a model is not found """ if is_timm_available() and isinstance(error, RuntimeError) and "Unknown model" in error.args[0]: return "timm" elif ( is_transformers_available() and isinstance(error, OSError) and "does not appear to have a file named" in error.args[0] ): return "transformers" else: return "unknown"
def create_empty_model(model_name: str, library_name: str, trust_remote_code: bool = False, access_token: str = None): """ Creates an empty model in full precision from its parent library on the `Hub` to calculate the overall memory consumption.
Args: model_name (`str`): The model name on the Hub library_name (`str`): The library the model has an integration with, such as `transformers`. Will be used if `model_name` has no metadata on the Hub to determine the library. trust_remote_code (`bool`, `optional`, defaults to `False`): Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set to `True` for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. access_token (`str`, `optional`, defaults to `None`): The access token to use to access private or gated models on the Hub. (for use on the Gradio app)
Returns: `torch.nn.Module`: The torch model that has been initialized on the `meta` device.
""" model_info = verify_on_hub(model_name, access_token) # Simplified errors if model_info == "gated": raise GatedRepoError( f"Repo for model `{model_name}` is gated. You must be authenticated to access it. Please run `huggingface-cli login`." ) elif model_info == "repo": raise RepositoryNotFoundError( f"Repo for model `{model_name}` does not exist on the Hub. If you are trying to access a private repo," " make sure you are authenticated via `huggingface-cli login` and have access." ) if library_name is None: library_name = getattr(model_info, "library_name", False) if not library_name: raise ValueError( f"Model `{model_name}` does not have any library metadata on the Hub, please manually pass in a `--library_name` to use (such as `transformers`)" ) if library_name == "transformers": if not is_transformers_available(): raise ImportError( f"To check `{model_name}`, `transformers` must be installed. Please install it via `pip install transformers`" ) print(f"Loading pretrained config for `{model_name}` from `transformers`...") if model_info.config is None: raise RuntimeError(f"Tried to load `{model_name}` with `transformers` but it does not have any metadata.")
auto_map = model_info.config.get("auto_map", False) config = AutoConfig.from_pretrained(model_name, trust_remote_code=trust_remote_code, token=access_token) with init_empty_weights(): # remote code could specify a specific `AutoModel` class in the `auto_map` constructor = AutoModel if isinstance(auto_map, dict): value = None for key in auto_map.keys(): if key.startswith("AutoModelFor"): value = key break if value is not None: constructor = getattr(transformers, value) # we need to pass the dtype, otherwise it is going to use the torch_dtype that is saved in the config model = constructor.from_config(config, torch_dtype=torch.float32, trust_remote_code=trust_remote_code) elif library_name == "timm": if not is_timm_available(): raise ImportError( f"To check `{model_name}`, `timm` must be installed. Please install it via `pip install timm`" ) print(f"Loading pretrained config for `{model_name}` from `timm`...") with init_empty_weights(): model = timm.create_model(model_name, pretrained=False) else: raise ValueError( f"Library `{library_name}` is not supported yet, please open an issue on GitHub for us to add support." ) return model
def create_ascii_table(headers: list, rows: list, title: str): "Creates a pretty table from a list of rows, minimal version of `tabulate`." sep_char, in_between = "│", "─" column_widths = [] for i in range(len(headers)): column_values = [row[i] for row in rows] + [headers[i]] max_column_width = max(len(value) for value in column_values) column_widths.append(max_column_width)
formats = [f"%{column_widths[i]}s" for i in range(len(rows[0]))]
pattern = f"{sep_char}{sep_char.join(formats)}{sep_char}" diff = 0
def make_row(left_char, middle_char, right_char): return f"{left_char}{middle_char.join([in_between * n for n in column_widths])}{in_between * diff}{right_char}"
separator = make_row("├", "┼", "┤") if len(title) > sum(column_widths): diff = abs(len(title) - len(separator)) column_widths[-1] += diff
# Update with diff separator = make_row("├", "┼", "┤") initial_rows = [ make_row("┌", in_between, "┐"), f"{sep_char}{title.center(len(separator) - 2)}{sep_char}", make_row("├", "┬", "┤"), ] table = "\n".join(initial_rows) + "\n" column_widths[-1] += diff centered_line = [text.center(column_widths[i]) for i, text in enumerate(headers)] table += f"{pattern % tuple(centered_line)}\n{separator}\n" for i, line in enumerate(rows): centered_line = [t.center(column_widths[i]) for i, t in enumerate(line)] table += f"{pattern % tuple(centered_line)}\n" table += f"└{'┴'.join([in_between * n for n in column_widths])}┘"
return table
def estimate_command_parser(subparsers=None): if subparsers is not None: parser = subparsers.add_parser("estimate-memory") else: parser = CustomArgumentParser(description="Model size estimator for fitting a model onto CUDA memory.")
parser.add_argument("model_name", type=str, help="The model name on the Hugging Face Hub.") parser.add_argument( "--library_name", type=str, help="The library the model has an integration with, such as `transformers`, needed only if this information is not stored on the Hub.", choices=["timm", "transformers"], ) parser.add_argument( "--dtypes", type=str, nargs="+", default=["float32", "float16", "int8", "int4"], help="The dtypes to use for the model, must be one (or many) of `float32`, `float16`, `int8`, and `int4`", choices=["float32", "float16", "int8", "int4"], ) parser.add_argument( "--trust_remote_code", action="store_true", help="""Whether or not to allow for custom models defined on the Hub in their own modeling files. This flag should only be used for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine.""", default=False, )
if subparsers is not None: parser.set_defaults(func=estimate_command) return parser
def estimate_training_usage(bytes: int, mixed_precision: str, msamp_config: str = None) -> dict: """ Given an amount of `bytes` and `mixed_precision`, calculates how much training memory is needed for a batch size of 1.
Args: bytes (`int`): The size of the model being trained. mixed_precision (`str`): The mixed precision that would be ran. msamp_config (`str`): The msamp config to estimate the training memory for if `mixed_precision` is set to `"fp8"`. """ memory_sizes = {"model": -1, "optimizer": -1, "gradients": -1, "step": -1} fp32_size = bytes fp16_size = bytes // 2
if mixed_precision == "float32": memory_sizes["model"] = fp32_size memory_sizes["gradients"] = fp32_size memory_sizes["optimizer"] = fp32_size * 2 memory_sizes["step"] = fp32_size * 4 elif mixed_precision in ("float16", "bfloat16") or (mixed_precision == "fp8" and msamp_config is None): # With native `TransformersEngine`, there is no memory savings with FP8 # With mixed precision training, the model has weights stored # in FP16 and FP32 memory_sizes["model"] = fp32_size # 1.5 from weight gradient + computation (GEMM) memory_sizes["gradients"] = fp32_size + fp16_size # 2x from optimizer states memory_sizes["optimizer"] = fp32_size * 2 # Optimizer states memory_sizes["step"] = memory_sizes["optimizer"] return memory_sizes
def gather_data(args): "Creates an empty model and gathers the data for the sizes" try: model = create_empty_model( args.model_name, library_name=args.library_name, trust_remote_code=args.trust_remote_code ) except (RuntimeError, OSError) as e: library = check_has_model(e) if library != "unknown": raise RuntimeError( f"Tried to load `{args.model_name}` with `{library}` but a possible model to load was not found inside the repo." ) raise e
total_size, largest_layer = calculate_maximum_sizes(model)
data = []
for dtype in args.dtypes: dtype_total_size = total_size dtype_largest_layer = largest_layer[0] dtype_training_size = estimate_training_usage(dtype_total_size, dtype) if dtype == "float16": dtype_total_size /= 2 dtype_largest_layer /= 2 elif dtype == "int8": dtype_total_size /= 4 dtype_largest_layer /= 4 elif dtype == "int4": dtype_total_size /= 8 dtype_largest_layer /= 8 data.append([dtype, dtype_largest_layer, dtype_total_size, dtype_training_size]) return data
def estimate_command(args): data = gather_data(args) for row in data: for i, item in enumerate(row): if isinstance(item, (int, float)): row[i] = convert_bytes(item) elif isinstance(item, dict): training_usage = max(item.values()) row[i] = convert_bytes(training_usage) if training_usage != -1 else "N/A"
headers = ["dtype", "Largest Layer", "Total Size", "Training using Adam"]
title = f"Memory Usage for loading `{args.model_name}`" table = create_ascii_table(headers, data, title) print(table)
def main(): parser = estimate_command_parser() args = parser.parse_args() estimate_command(args)
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208#!/usr/bin/env python
# Copyright 2021 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import argparseimport importlibimport loggingimport osimport subprocessimport sysfrom pathlib import Path
import psutilimport torch
from accelerate.commands.config import default_config_file, load_config_from_filefrom accelerate.commands.config.config_args import SageMakerConfigfrom accelerate.commands.config.config_utils import DYNAMO_BACKENDSfrom accelerate.commands.utils import CustomArgumentParserfrom accelerate.state import get_int_from_envfrom accelerate.utils import ( ComputeEnvironment, DistributedType, PrepareForLaunch, _filter_args, check_cuda_p2p_ib_support, convert_dict_to_env_variables, is_bf16_available, is_deepspeed_available, is_hpu_available, is_mlu_available, is_musa_available, is_npu_available, is_rich_available, is_sagemaker_available, is_sdaa_available, is_torch_xla_available, is_xpu_available, patch_environment, prepare_deepspeed_cmd_env, prepare_multi_gpu_env, prepare_sagemager_args_inputs, prepare_simple_launcher_cmd_env, prepare_tpu, str_to_bool,)from accelerate.utils.constants import DEEPSPEED_MULTINODE_LAUNCHERS, TORCH_DYNAMO_MODES
if is_rich_available(): from rich import get_console from rich.logging import RichHandler
FORMAT = "%(message)s" logging.basicConfig(format=FORMAT, datefmt="[%X]", handlers=[RichHandler()])
logger = logging.getLogger(__name__)
options_to_group = { "multi_gpu": "Distributed GPUs", "tpu": "TPU", "use_deepspeed": "DeepSpeed Arguments", "use_fsdp": "FSDP Arguments", "use_megatron_lm": "Megatron-LM Arguments", "fp8_backend": "FP8 Arguments",}
def clean_option(option): "Finds all cases of - after the first two characters and changes them to _" if "fp8_backend" in option: option = "--fp8_backend" if option.startswith("--"): return option[2:].replace("-", "_")
class CustomHelpFormatter(argparse.HelpFormatter): """ This is a custom help formatter that will hide all arguments that are not used in the command line when the help is called. This is useful for the case where the user is using a specific platform and only wants to see the arguments for that platform. """
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.titles = [ "Hardware Selection Arguments", "Resource Selection Arguments", "Training Paradigm Arguments", "positional arguments", "optional arguments", ]
def add_argument(self, action: argparse.Action): if "accelerate" in sys.argv[0] and "launch" in sys.argv[1:]: args = sys.argv[2:] else: args = sys.argv[1:]
if len(args) > 1: args = list(map(clean_option, args)) used_platforms = [arg for arg in args if arg in options_to_group.keys()] used_titles = [options_to_group[o] for o in used_platforms] if action.container.title not in self.titles + used_titles: action.help = argparse.SUPPRESS elif action.container.title == "Hardware Selection Arguments": if set(action.option_strings).isdisjoint(set(args)): action.help = argparse.SUPPRESS else: action.help = action.help + " (currently selected)" elif action.container.title == "Training Paradigm Arguments": if set(action.option_strings).isdisjoint(set(args)): action.help = argparse.SUPPRESS else: action.help = action.help + " (currently selected)"
action.option_strings = [s for s in action.option_strings if "-" not in s[2:]] super().add_argument(action)
def end_section(self): if len(self._current_section.items) < 2: self._current_section.items = [] self._current_section.heading = "" super().end_section()
def launch_command_parser(subparsers=None): description = "Launch a python script in a distributed scenario. Arguments can be passed in with either hyphens (`--num-processes=2`) or underscores (`--num_processes=2`)" if subparsers is not None: parser = subparsers.add_parser( "launch", description=description, add_help=False, allow_abbrev=False, formatter_class=CustomHelpFormatter ) else: parser = CustomArgumentParser( "Accelerate launch command", description=description, add_help=False, allow_abbrev=False, formatter_class=CustomHelpFormatter, )
parser.add_argument("-h", "--help", action="help", help="Show this help message and exit.")
parser.add_argument( "--config_file", default=None, help="The config file to use for the default values in the launching script.", ) parser.add_argument( "--quiet", "-q", action="store_true", help="Silence subprocess errors from the launch stack trace and only show the relevant tracebacks. (Only applicable to DeepSpeed and single-process configurations)", ) # Hardware selection arguments hardware_args = parser.add_argument_group( "Hardware Selection Arguments", "Arguments for selecting the hardware to be used." ) hardware_args.add_argument( "--cpu", default=False, action="store_true", help="Whether or not to force the training on the CPU." ) hardware_args.add_argument( "--multi_gpu", default=False, action="store_true", help="Whether or not this should launch a distributed GPU training.", ) hardware_args.add_argument( "--tpu", default=False, action="store_true", help="Whether or not this should launch a TPU training." ) hardware_args.add_argument( "--ipex", default=False, action="store_true", help="Whether or not this should launch a Intel PyTorch Extension (IPEX) training.", )
# Resource selection arguments resource_args = parser.add_argument_group( "Resource Selection Arguments", "Arguments for fine-tuning how available hardware should be used." ) resource_args.add_argument( "--mixed_precision", type=str, choices=["no", "fp16", "bf16", "fp8"], help="Whether or not to use mixed precision training. " "Choose between FP16 and BF16 (bfloat16) training. " "BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.", ) resource_args.add_argument( "--num_processes", type=int, default=None, help="The total number of processes to be launched in parallel." ) resource_args.add_argument( "--num_machines", type=int, default=None, help="The total number of machines used in this training." ) resource_args.add_argument( "--num_cpu_threads_per_process", type=int, default=None, help="The number of CPU threads per process. Can be tuned for optimal performance.", ) resource_args.add_argument( "--enable_cpu_affinity", default=False, action="store_true", help="Whether or not CPU affinity and balancing should be enabled. Currently only supported on NVIDIA hardware.", ) # Dynamo arguments resource_args.add_argument( "--dynamo_backend", type=str, choices=["no"] + [b.lower() for b in DYNAMO_BACKENDS], help="Choose a backend to optimize your training with dynamo, see more at " "https://github.com/pytorch/torchdynamo.", ) resource_args.add_argument( "--dynamo_mode", type=str, default="default", choices=TORCH_DYNAMO_MODES, help="Choose a mode to optimize your training with dynamo.", ) resource_args.add_argument( "--dynamo_use_fullgraph", default=False, action="store_true", help="Whether to use full graph mode for dynamo or it is ok to break model into several subgraphs", ) resource_args.add_argument( "--dynamo_use_dynamic", default=False, action="store_true", help="Whether to enable dynamic shape tracing.", ) resource_args.add_argument( "--dynamo_use_regional_compilation", default=False, action="store_true", help="Whether to enable regional compilation.", )
# Training Paradigm arguments paradigm_args = parser.add_argument_group( "Training Paradigm Arguments", "Arguments for selecting which training paradigm to be used." ) paradigm_args.add_argument( "--use_deepspeed", default=False, action="store_true", help="Whether to use deepspeed.", ) paradigm_args.add_argument( "--use_fsdp", default=False, action="store_true", help="Whether to use fsdp.", ) paradigm_args.add_argument( "--use_megatron_lm", default=False, action="store_true", help="Whether to use Megatron-LM.", )
paradigm_args.add_argument( "--use_xpu", default=None, action="store_true", help="Whether to use IPEX plugin to speed up training on XPU specifically. This argument is deprecated and ignored, will be removed in Accelerate v1.20.", )
# distributed GPU training arguments distributed_args = parser.add_argument_group("Distributed GPUs", "Arguments related to distributed GPU training.") distributed_args.add_argument( "--gpu_ids", default=None, help="What GPUs (by id) should be used for training on this machine as a comma-separated list", ) distributed_args.add_argument( "--same_network", default=False, action="store_true", help="Whether all machines used for multinode training exist on the same local network.", ) distributed_args.add_argument( "--machine_rank", type=int, default=None, help="The rank of the machine on which this script is launched." ) distributed_args.add_argument( "--main_process_ip", type=str, default=None, help="The IP address of the machine of rank 0." ) distributed_args.add_argument( "--main_process_port", type=int, default=None, help="The port to use to communicate with the machine of rank 0.", ) distributed_args.add_argument( "-t", "--tee", default="0", type=str, help="Tee std streams into a log file and also to console.", ) distributed_args.add_argument( "--log_dir", type=str, default=None, help=( "Base directory to use for log files when using torchrun/torch.distributed.run as launcher. " "Use with --tee to redirect std streams info log files." ), ) distributed_args.add_argument( "--role", type=str, default="default", help="User-defined role for the workers.", ) # Rendezvous related arguments distributed_args.add_argument( "--rdzv_backend", type=str, default="static", help="The rendezvous method to use, such as 'static' (the default) or 'c10d'", ) distributed_args.add_argument( "--rdzv_conf", type=str, default="", help="Additional rendezvous configuration (<key1>=<value1>,<key2>=<value2>,...).", ) distributed_args.add_argument( "--max_restarts", type=int, default=0, help="Maximum number of worker group restarts before failing.", ) distributed_args.add_argument( "--monitor_interval", type=float, default=0.1, help="Interval, in seconds, to monitor the state of workers.", ) parser.add_argument( "-m", "--module", action="store_true", help="Change each process to interpret the launch script as a Python module, executing with the same behavior as 'python -m'.", ) parser.add_argument( "--no_python", action="store_true", help="Skip prepending the training script with 'python' - just execute it directly. Useful when the script is not a Python script.", )
# TPU arguments tpu_args = parser.add_argument_group("TPU", "Arguments related to TPU.") tpu_args.add_argument( "--tpu_cluster", action="store_true", dest="tpu_use_cluster", help="Whether to use a GCP TPU pod for training.", ) tpu_args.add_argument( "--no_tpu_cluster", action="store_false", dest="tpu_use_cluster", help="Should not be passed explicitly, this is for internal use only.", ) tpu_args.add_argument( "--tpu_use_sudo", action="store_true", help="Whether to use `sudo` when running the TPU training script in each pod.", ) tpu_args.add_argument( "--vm", type=str, action="append", help=( "List of single Compute VM instance names. " "If not provided we assume usage of instance groups. For TPU pods." ), ) tpu_args.add_argument( "--env", type=str, action="append", help="List of environment variables to set on the Compute VM instances. For TPU pods.", ) tpu_args.add_argument( "--main_training_function", type=str, default=None, help="The name of the main function to be executed in your script (only for TPU training).", ) tpu_args.add_argument( "--downcast_bf16", action="store_true", help="Whether when using bf16 precision on TPUs if both float and double tensors are cast to bfloat16 or if double tensors remain as float32.", )
# DeepSpeed arguments deepspeed_args = parser.add_argument_group("DeepSpeed Arguments", "Arguments related to DeepSpeed.") deepspeed_args.add_argument( "--deepspeed_config_file", default=None, type=str, help="DeepSpeed config file.", ) deepspeed_args.add_argument( "--zero_stage", default=None, type=int, help="DeepSpeed's ZeRO optimization stage (useful only when `use_deepspeed` flag is passed). " "If unspecified, will default to `2`.", ) deepspeed_args.add_argument( "--offload_optimizer_device", default=None, type=str, help="Decides where (none|cpu|nvme) to offload optimizer states (useful only when `use_deepspeed` flag is passed). " "If unspecified, will default to 'none'.", ) deepspeed_args.add_argument( "--offload_param_device", default=None, type=str, help="Decides where (none|cpu|nvme) to offload parameters (useful only when `use_deepspeed` flag is passed). " "If unspecified, will default to 'none'.", ) deepspeed_args.add_argument( "--offload_optimizer_nvme_path", default=None, type=str, help="Decides Nvme Path to offload optimizer states (useful only when `use_deepspeed` flag is passed). " "If unspecified, will default to 'none'.", ) deepspeed_args.add_argument( "--offload_param_nvme_path", default=None, type=str, help="Decides Nvme Path to offload parameters (useful only when `use_deepspeed` flag is passed). " "If unspecified, will default to 'none'.", ) deepspeed_args.add_argument( "--gradient_accumulation_steps", default=None, type=int, help="No of gradient_accumulation_steps used in your training script (useful only when `use_deepspeed` flag is passed). " "If unspecified, will default to `1`.", ) deepspeed_args.add_argument( "--gradient_clipping", default=None, type=float, help="gradient clipping value used in your training script (useful only when `use_deepspeed` flag is passed). " "If unspecified, will default to `1.0`.", ) deepspeed_args.add_argument( "--zero3_init_flag", default=None, type=str, help="Decides Whether (true|false) to enable `deepspeed.zero.Init` for constructing massive models. " "Only applicable with DeepSpeed ZeRO Stage-3. If unspecified, will default to `true`.", ) deepspeed_args.add_argument( "--zero3_save_16bit_model", default=None, type=str, help="Decides Whether (true|false) to save 16-bit model weights when using ZeRO Stage-3. " "Only applicable with DeepSpeed ZeRO Stage-3. If unspecified, will default to `false`.", ) deepspeed_args.add_argument( "--deepspeed_hostfile", default=None, type=str, help="DeepSpeed hostfile for configuring multi-node compute resources.", ) deepspeed_args.add_argument( "--deepspeed_exclusion_filter", default=None, type=str, help="DeepSpeed exclusion filter string when using mutli-node setup.", ) deepspeed_args.add_argument( "--deepspeed_inclusion_filter", default=None, type=str, help="DeepSpeed inclusion filter string when using mutli-node setup.", ) deepspeed_args.add_argument( "--deepspeed_multinode_launcher", default=None, type=str, help="DeepSpeed multi-node launcher to use, e.g. `pdsh`, `standard`, `openmpi`, `mvapich`, `mpich`, `slurm`, `nossh` (requires DeepSpeed >= 0.14.5). If unspecified, will default to `pdsh`.", ) deepspeed_args.add_argument( "--deepspeed_moe_layer_cls_names", default=None, type=str, help="comma-separated list of transformer MoE layer class names (case-sensitive) to wrap ,e.g, `MixtralSparseMoeBlock`, `Qwen2MoeSparseMoeBlock`, `JetMoEAttention,JetMoEBlock` ..." " (useful only when `use_deepspeed` flag is passed).", )
# fsdp arguments fsdp_args = parser.add_argument_group("FSDP Arguments", "Arguments related to Fully Shared Data Parallelism.") fsdp_args.add_argument( "--fsdp_version", type=str, default="1", choices=["1", "2"], help="FSDP version to use. (useful only when `use_fsdp` flag is passed).", ) fsdp_args.add_argument( "--fsdp_offload_params", default="false", type=str, help="Decides Whether (true|false) to offload parameters and gradients to CPU. (useful only when `use_fsdp` flag is passed).", ) fsdp_args.add_argument( "--fsdp_min_num_params", type=int, default=1e8, help="FSDP's minimum number of parameters for Default Auto Wrapping. (useful only when `use_fsdp` flag is passed).", ) # We enable this for backwards compatibility, throw a warning if this is set in `FullyShardedDataParallelPlugin` fsdp_args.add_argument( "--fsdp_sharding_strategy", type=str, default="FULL_SHARD", help="FSDP's sharding strategy. (useful only when `use_fsdp` flag is passed and `fsdp_version=1`).", ) fsdp_args.add_argument( "--fsdp_reshard_after_forward", type=str, default="true", help="FSDP's Reshard After Forward Strategy. (useful only when `use_fsdp` flag is passed). Supports either boolean (FSDP2) or `FULL_SHARD | SHARD_GRAD_OP | NO_RESHARD` (FSDP1).", ) fsdp_args.add_argument( "--fsdp_auto_wrap_policy", type=str, default=None, help="FSDP's auto wrap policy. (useful only when `use_fsdp` flag is passed).", ) fsdp_args.add_argument( "--fsdp_transformer_layer_cls_to_wrap", default=None, type=str, help="Transformer layer class name (case-sensitive) to wrap ,e.g, `BertLayer`, `GPTJBlock`, `T5Block` .... " "(useful only when `use_fsdp` flag is passed).", ) fsdp_args.add_argument( "--fsdp_backward_prefetch", default=None, type=str, help="FSDP's backward prefetch policy. (useful only when `use_fsdp` flag is passed).", ) fsdp_args.add_argument( "--fsdp_state_dict_type", default=None, type=str, help="FSDP's state dict type. (useful only when `use_fsdp` flag is passed).", ) fsdp_args.add_argument( "--fsdp_forward_prefetch", default="false", type=str, help="If True, then FSDP explicitly prefetches the next upcoming " "all-gather while executing in the forward pass (useful only when `use_fsdp` flag is passed).", ) fsdp_args.add_argument( "--fsdp_use_orig_params", default="true", type=str, help="If True, allows non-uniform `requires_grad` during init, which means support for interspersed frozen and trainable paramteres." " (useful only when `use_fsdp` flag is passed).", ) fsdp_args.add_argument( "--fsdp_cpu_ram_efficient_loading", default="true", type=str, help="If True, only the first process loads the pretrained model checkoint while all other processes have empty weights. " "Only applicable for 🤗 Transformers. When using this, `--fsdp_sync_module_states` needs to True. " "(useful only when `use_fsdp` flag is passed).", ) fsdp_args.add_argument( "--fsdp_sync_module_states", default="true", type=str, help="If True, each individually wrapped FSDP unit will broadcast module parameters from rank 0." " (useful only when `use_fsdp` flag is passed).", ) fsdp_args.add_argument( "--fsdp_activation_checkpointing", default="false", type=str, help="Decides Whether (true|false) intermediate activations are freed during the forward pass, and a checkpoint is left as a placeholder. (useful only when `use_fsdp` flag is passed).", )
# megatron_lm args megatron_lm_args = parser.add_argument_group("Megatron-LM Arguments", "Arguments related to Megatron-LM.") megatron_lm_args.add_argument( "--megatron_lm_tp_degree", type=int, default=1, help="Megatron-LM's Tensor Parallelism (TP) degree. (useful only when `use_megatron_lm` flag is passed).", ) megatron_lm_args.add_argument( "--megatron_lm_pp_degree", type=int, default=1, help="Megatron-LM's Pipeline Parallelism (PP) degree. (useful only when `use_megatron_lm` flag is passed).", ) megatron_lm_args.add_argument( "--megatron_lm_num_micro_batches", type=int, default=None, help="Megatron-LM's number of micro batches when PP degree > 1. (useful only when `use_megatron_lm` flag is passed).", ) megatron_lm_args.add_argument( "--megatron_lm_sequence_parallelism", default=None, type=str, help="Decides Whether (true|false) to enable Sequence Parallelism when TP degree > 1. " "(useful only when `use_megatron_lm` flag is passed).", ) megatron_lm_args.add_argument( "--megatron_lm_recompute_activations", default=None, type=str, help="Decides Whether (true|false) to enable Selective Activation Recomputation. " "(useful only when `use_megatron_lm` flag is passed).", ) megatron_lm_args.add_argument( "--megatron_lm_use_distributed_optimizer", default=None, type=str, help="Decides Whether (true|false) to use distributed optimizer " "which shards optimizer state and gradients across Data Pralellel (DP) ranks. " "(useful only when `use_megatron_lm` flag is passed).", ) megatron_lm_args.add_argument( "--megatron_lm_gradient_clipping", default=1.0, type=float, help="Megatron-LM's gradient clipping value based on global L2 Norm (0 to disable). " "(useful only when `use_megatron_lm` flag is passed).", )
# FP8 arguments fp8_args = parser.add_argument_group( "FP8 Arguments", "Arguments related to FP8 training (requires `--mixed_precision=fp8`)" ) fp8_args.add_argument( "--fp8_backend", type=str, choices=["te", "msamp"], help="Choose a backend to train with FP8 (te: TransformerEngine, msamp: MS-AMP)", ) fp8_args.add_argument( "--fp8_use_autocast_during_eval", default=False, action="store_true", help="Whether to use FP8 autocast during eval mode (useful only when `--fp8_backend=te` is passed). Generally better metrics are found when this is not passed.", ) fp8_args.add_argument( "--fp8_margin", type=int, default=0, help="The margin to use for the gradient scaling (useful only when `--fp8_backend=te` is passed).", ) fp8_args.add_argument( "--fp8_interval", type=int, default=1, help="The interval to use for how often the scaling factor is recomputed (useful only when `--fp8_backend=te` is passed).", ) fp8_args.add_argument( "--fp8_format", type=str, default="E4M3", choices=["E4M3", "HYBRID"], help="The format to use for the FP8 recipe (useful only when `--fp8_backend=te` is passed).", ) fp8_args.add_argument( "--fp8_amax_history_len", type=int, default=1024, help="The length of the history to use for the scaling factor computation (useful only when `--fp8_backend=te` is passed).", ) fp8_args.add_argument( "--fp8_amax_compute_algo", type=str, default="most_recent", choices=["max", "most_recent"], help="The algorithm to use for the scaling factor computation. (useful only when `--fp8_backend=te` is passed).", ) fp8_args.add_argument( "--fp8_override_linear_precision", type=lambda x: tuple(map(str_to_bool, x.split(","))), default=(False, False, False), help="Whether or not to execute `fprop`, `dgrad`, and `wgrad` GEMMS in higher precision. Should be passed in a comma-separated string of booleans (useful only when `--fp8_backend=te` is passed).", ) fp8_args.add_argument( "--fp8_opt_level", type=str, default="O2", choices=["O1", "O2"], help="What level of 8-bit collective communication should be used with MS-AMP (useful only when `--fp8_backend=msamp` is passed).", )
# AWS arguments aws_args = parser.add_argument_group("AWS Arguments", "Arguments related to AWS.") aws_args.add_argument( "--aws_access_key_id", type=str, default=None, help="The AWS_ACCESS_KEY_ID used to launch the Amazon SageMaker training job", ) aws_args.add_argument( "--aws_secret_access_key", type=str, default=None, help="The AWS_SECRET_ACCESS_KEY used to launch the Amazon SageMaker training job.", ) parser.add_argument( "--debug", action="store_true", help="Whether to print out the torch.distributed stack trace when something fails.", ) parser.add_argument( "training_script", type=str, help=( "The full path to the script to be launched in parallel, followed by all the arguments for the training " "script." ), )
# MPI arguments mpirun_args = parser.add_argument_group("MPI Arguments", "Arguments related to mpirun for Multi-CPU") mpirun_args.add_argument( "--mpirun_hostfile", type=str, default=None, help="Location for a hostfile for using Accelerate to launch a multi-CPU training job with mpirun. This will " "get passed to the MPI --hostfile or -f parameter, depending on which MPI program is installed.", ) mpirun_args.add_argument( "--mpirun_ccl", type=int, default=1, help="The number of oneCCL worker threads when using Accelerate to launch multi-CPU training with mpirun.", )
# Other arguments of the training scripts parser.add_argument("training_script_args", nargs=argparse.REMAINDER, help="Arguments of the training script.")
if subparsers is not None: parser.set_defaults(func=launch_command) return parser
def simple_launcher(args): cmd, current_env = prepare_simple_launcher_cmd_env(args)
process = subprocess.Popen(cmd, env=current_env) process.wait() if process.returncode != 0: if not args.quiet: raise subprocess.CalledProcessError(returncode=process.returncode, cmd=cmd) else: sys.exit(1)
def multi_gpu_launcher(args): import torch.distributed.run as distrib_run
current_env = prepare_multi_gpu_env(args) if not check_cuda_p2p_ib_support(): message = "Using RTX 4000 series which doesn't support faster communication speedups. Ensuring P2P and IB communications are disabled." warn = False if "NCCL_P2P_DISABLE" not in current_env: current_env["NCCL_P2P_DISABLE"] = "1" warn = True if "NCCL_IB_DISABLE" not in current_env: current_env["NCCL_IB_DISABLE"] = "1" warn = True if warn: logger.warning(message)
debug = getattr(args, "debug", False) args = _filter_args( args, distrib_run.get_args_parser(), ["--training_script", args.training_script, "--training_script_args", args.training_script_args], )
with patch_environment(**current_env): try: distrib_run.run(args) except Exception: if is_rich_available() and debug: console = get_console() console.print("\n[bold red]Using --debug, `torch.distributed` Stack Trace:[/bold red]") console.print_exception(suppress=[__file__], show_locals=False) else: raise
def deepspeed_launcher(args): import torch.distributed.run as distrib_run
if not is_deepspeed_available(): raise ImportError("DeepSpeed is not installed => run `pip3 install deepspeed` or build it from source.") else: from deepspeed.launcher.runner import DEEPSPEED_ENVIRONMENT_NAME
cmd, current_env = prepare_deepspeed_cmd_env(args) if not check_cuda_p2p_ib_support(): message = "Using RTX 4000 series which doesn't support faster communication speedups. Ensuring P2P and IB communications are disabled." warn = False if "NCCL_P2P_DISABLE" not in current_env: current_env["NCCL_P2P_DISABLE"] = "1" warn = True if "NCCL_IB_DISABLE" not in current_env: current_env["NCCL_IB_DISABLE"] = "1" warn = True if warn: logger.warning(message)
if args.num_machines > 1 and args.deepspeed_multinode_launcher != DEEPSPEED_MULTINODE_LAUNCHERS[1]: with open(DEEPSPEED_ENVIRONMENT_NAME, "a") as f: valid_env_items = convert_dict_to_env_variables(current_env) if len(valid_env_items) > 1: f.writelines(valid_env_items)
process = subprocess.Popen(cmd, env=current_env) process.wait() if process.returncode != 0: if not args.quiet: raise subprocess.CalledProcessError(returncode=process.returncode, cmd=cmd) else: sys.exit(1) else: debug = getattr(args, "debug", False) args = _filter_args( args, distrib_run.get_args_parser(), ["--training_script", args.training_script, "--training_script_args", args.training_script_args], ) with patch_environment(**current_env): try: distrib_run.run(args) except Exception: if is_rich_available() and debug: console = get_console() console.print("\n[bold red]Using --debug, `torch.distributed` Stack Trace:[/bold red]") console.print_exception(suppress=[__file__], show_locals=False) else: raise
def tpu_launcher(args): import torch_xla.distributed.xla_multiprocessing as xmp from torch_xla import device_count
if args.no_python: raise ValueError("--no_python cannot be used with TPU launcher")
args, current_env = prepare_tpu(args, {})
if args.module: mod_name = args.training_script else: # Import training_script as a module script_path = Path(args.training_script) sys.path.append(str(script_path.parent.resolve())) mod_name = script_path.stem
mod = importlib.import_module(mod_name) if not hasattr(mod, args.main_training_function): raise ValueError( f"Your training script should have a function named {args.main_training_function}, or you should pass a " "different value to `--main_training_function`." ) if args.num_processes and args.num_processes != device_count(): raise ValueError( f"Number of processes ({args.num_processes}) must match the number of TPU devices ({device_count()})" )
# Patch sys.argv sys.argv = [mod.__file__] + args.training_script_args
main_function = getattr(mod, args.main_training_function) with patch_environment(**current_env): xmp.spawn(PrepareForLaunch(main_function), args=())
def tpu_pod_launcher(args): from torch_xla.distributed import xla_dist
current_env = {} args, current_env = prepare_tpu(args, current_env, True) debug = getattr(args, "debug", False)
training_script = args.training_script training_script_args = args.training_script_args new_args = _filter_args( args, xla_dist.get_args_parser(), ["--tpu", args.tpu_name, "--positional", "", "--restart-tpuvm-pod-server"] )
if args.tpu_use_sudo: new_cmd = ["sudo"] else: new_cmd = []
new_cmd += [ "accelerate-launch", "--tpu", "--no_tpu_cluster", "--num_machines", "1", "--mixed_precision", "no", "--dynamo_backend", "no", "--num_processes", str(args.num_processes), "--main_training_function", str(args.main_training_function), training_script, ] + training_script_args
new_args.positional = new_cmd bad_flags = "" for arg in vars(new_args): if arg.startswith("docker_"): value = getattr(new_args, arg) if value != "" and value is not None: bad_flags += f'{arg}="{value}"\n' if bad_flags != "": raise ValueError( f"Docker containers are not supported for TPU pod launcher currently, please remove the following flags:\n{bad_flags}" ) new_args.env = [f"{k}={v}" for k, v in current_env.items()] new_args.env.append("ACCELERATE_IN_TPU_POD=1") try: xla_dist.resolve_and_execute(new_args) except Exception: if is_rich_available() and debug: console = get_console() console.print("\n[bold red]Using --debug, `torch_xla.xla_dist` Stack Trace:[/bold red]") console.print_exception(suppress=[__file__], show_locals=False) else: raise
def sagemaker_launcher(sagemaker_config: SageMakerConfig, args): if not is_sagemaker_available(): raise ImportError( "Please install sagemaker to be able to launch training on Amazon SageMaker with `pip install accelerate[sagemaker]`" ) if args.module or args.no_python: raise ValueError( "SageMaker requires a python training script file and cannot be used with --module or --no_python" )
from sagemaker.huggingface import HuggingFace
args, sagemaker_inputs = prepare_sagemager_args_inputs(sagemaker_config, args)
huggingface_estimator = HuggingFace(**args)
huggingface_estimator.fit(inputs=sagemaker_inputs) print(f"You can find your model data at: {huggingface_estimator.model_data}")
def _validate_launch_command(args): # Sanity checks if sum([args.multi_gpu, args.cpu, args.tpu, args.use_deepspeed, args.use_fsdp]) > 1: raise ValueError( "You can only use one of `--cpu`, `--multi_gpu`, `--tpu`, `--use_deepspeed`, `--use_fsdp` at a time." ) if args.multi_gpu and (args.num_processes is not None) and (args.num_processes < 2): raise ValueError("You need to use at least 2 processes to use `--multi_gpu`.")
defaults = None warned = [] mp_from_config_flag = False # Get the default from the config file. if args.config_file is not None or os.path.isfile(default_config_file) and not args.cpu: defaults = load_config_from_file(args.config_file) if ( not args.multi_gpu and not args.tpu and not args.tpu_use_cluster and not args.use_deepspeed and not args.use_fsdp and not args.use_megatron_lm ): args.use_deepspeed = defaults.distributed_type == DistributedType.DEEPSPEED args.multi_gpu = ( True if defaults.distributed_type in ( DistributedType.MULTI_GPU, DistributedType.MULTI_NPU, DistributedType.MULTI_MLU, DistributedType.MULTI_SDAA, DistributedType.MULTI_MUSA, DistributedType.MULTI_XPU, DistributedType.MULTI_HPU, ) else False ) args.tpu = defaults.distributed_type == DistributedType.XLA args.use_fsdp = defaults.distributed_type == DistributedType.FSDP args.use_megatron_lm = defaults.distributed_type == DistributedType.MEGATRON_LM args.tpu_use_cluster = defaults.tpu_use_cluster if args.tpu else False if args.gpu_ids is None: if defaults.gpu_ids is not None: args.gpu_ids = defaults.gpu_ids else: args.gpu_ids = "all"
if args.multi_gpu and args.num_machines is None: args.num_machines = defaults.num_machines
if len(args.gpu_ids.split(",")) < 2 and (args.gpu_ids != "all") and args.multi_gpu and args.num_machines <= 1: raise ValueError( "Less than two GPU ids were configured and tried to run on on multiple GPUs. " "Please ensure at least two are specified for `--gpu_ids`, or use `--gpu_ids='all'`." ) if defaults.compute_environment == ComputeEnvironment.LOCAL_MACHINE: # Update args with the defaults for name, attr in defaults.__dict__.items(): if isinstance(attr, dict): # Copy defaults.somedict.somearg to args.somearg and # defaults.fsdp_config.x to args.fsdp_x for key, value in attr.items(): if name == "fsdp_config" and not key.startswith("fsdp"): key = "fsdp_" + key elif name == "fp8_config" and not key.startswith("fp8"): key = "fp8_" + key if hasattr(args, "nondefault") and key not in args.nondefault: setattr(args, key, value) elif ( name not in ["compute_environment", "mixed_precision", "distributed_type"] and getattr(args, name, None) is None ): # Those args are handled separately setattr(args, name, attr) if not args.debug: args.debug = defaults.debug
if not args.mixed_precision: if defaults.mixed_precision is None: args.mixed_precision = "no" else: args.mixed_precision = defaults.mixed_precision mp_from_config_flag = True else: native_amp = is_bf16_available(True) if ( args.mixed_precision == "bf16" and not native_amp and not (args.tpu and is_torch_xla_available(check_is_tpu=True)) ): raise ValueError("bf16 mixed precision requires PyTorch >= 1.10 and a supported device.")
# Silently set the default here if args.dynamo_backend is None: args.dynamo_backend = "no" if args.num_processes == -1: raise ValueError("You need to manually pass in `--num_processes` using this config yaml.") else: if args.num_processes is None: if is_xpu_available(): args.num_processes = torch.xpu.device_count() elif is_mlu_available(): args.num_processes = torch.mlu.device_count() elif is_sdaa_available(): args.num_processes = torch.sdaa.device_count() elif is_musa_available(): args.num_processes = torch.musa.device_count() elif is_npu_available(): args.num_processes = torch.npu.device_count() elif is_hpu_available(): args.num_processes = torch.hpu.device_count() else: args.num_processes = torch.cuda.device_count() warned.append(f"\t`--num_processes` was set to a value of `{args.num_processes}`") if args.debug is None: args.debug = False if ( not args.multi_gpu and args.num_processes > 1 and ( (is_xpu_available() and torch.xpu.device_count() > 1) or (is_npu_available() and torch.npu.device_count() > 1) or (is_hpu_available() and torch.hpu.device_count() > 1) or (is_mlu_available() and torch.mlu.device_count() > 1) or (is_sdaa_available() and torch.sdaa.device_count() > 1) or (is_musa_available() and torch.musa.device_count() > 1) or (torch.cuda.is_available() and torch.cuda.device_count() > 1) ) ): warned.append( "\t\tMore than one GPU was found, enabling multi-GPU training.\n" "\t\tIf this was unintended please pass in `--num_processes=1`." ) args.multi_gpu = True if args.num_machines is None: warned.append("\t`--num_machines` was set to a value of `1`") args.num_machines = 1 if args.mixed_precision is None: warned.append("\t`--mixed_precision` was set to a value of `'no'`") args.mixed_precision = "no" if not hasattr(args, "use_cpu"): args.use_cpu = args.cpu if args.dynamo_backend is None: warned.append("\t`--dynamo_backend` was set to a value of `'no'`") args.dynamo_backend = "no" if args.debug: logger.debug("Running script in debug mode, expect distributed operations to be slightly slower.")
is_aws_env_disabled = defaults is None or ( defaults is not None and defaults.compute_environment != ComputeEnvironment.AMAZON_SAGEMAKER ) if is_aws_env_disabled and args.num_cpu_threads_per_process is None: args.num_cpu_threads_per_process = get_int_from_env(["OMP_NUM_THREADS"], 1) if args.use_cpu and args.num_processes >= 1 and get_int_from_env(["OMP_NUM_THREADS"], 0) == 0: local_size = get_int_from_env( ["MPI_LOCALNRANKS", "OMPI_COMM_WORLD_LOCAL_SIZE", "MV2_COMM_WORLD_LOCAL_SIZE"], max(int(args.num_processes / args.num_machines), 1), ) threads_per_process = int(psutil.cpu_count(logical=False) / local_size) if threads_per_process > 1: args.num_cpu_threads_per_process = threads_per_process warned.append( f"\t`--num_cpu_threads_per_process` was set to `{args.num_cpu_threads_per_process}` to improve out-of-box performance when training on CPUs" )
if args.use_xpu is not None: logger.warning( "use_xpu is deprecated and ignored, will be removed in Accelerate v1.20. " "XPU is a PyTorch native citizen now, we don't need extra argument to enable it any more." )
if any(warned): message = "The following values were not passed to `accelerate launch` and had defaults used instead:\n" message += "\n".join(warned) message += ( "\nTo avoid this warning pass in values for each of the problematic parameters or run `accelerate config`." ) logger.warning(message) return args, defaults, mp_from_config_flag
def launch_command(args): args, defaults, mp_from_config_flag = _validate_launch_command(args) # Use the proper launcher if args.use_deepspeed and not args.cpu: args.deepspeed_fields_from_accelerate_config = list(defaults.deepspeed_config.keys()) if defaults else [] if mp_from_config_flag: args.deepspeed_fields_from_accelerate_config.append("mixed_precision") args.deepspeed_fields_from_accelerate_config = ",".join(args.deepspeed_fields_from_accelerate_config) deepspeed_launcher(args) elif args.use_fsdp and not args.cpu: multi_gpu_launcher(args) elif args.use_megatron_lm and not args.cpu: multi_gpu_launcher(args) elif args.multi_gpu and not args.cpu: multi_gpu_launcher(args) elif args.tpu and not args.cpu: if args.tpu_use_cluster: tpu_pod_launcher(args) else: tpu_launcher(args) elif defaults is not None and defaults.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: sagemaker_launcher(defaults, args) else: simple_launcher(args)
def main(): parser = launch_command_parser() args = parser.parse_args() launch_command(args)
if __name__ == "__main__": main()1234567891011121314# Copyright 2022 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.from .selection_menu import BulletMenulib/python3.12/site-packages/accelerate-1.7.0.dist-info/INSTALLERAdded+1
lib/python3.12/site-packages/accelerate-1.7.0.dist-info/LICENSEAdded+201
lib/python3.12/site-packages/accelerate-1.7.0.dist-info/METADATAAdded+382
lib/python3.12/site-packages/accelerate-1.7.0.dist-info/RECORDAdded+177
lib/python3.12/site-packages/accelerate-1.7.0.dist-info/REQUESTEDAdded
lib/python3.12/site-packages/accelerate-1.7.0.dist-info/WHEELAdded+5
lib/python3.12/site-packages/accelerate-1.7.0.dist-info/entry_points.txtAdded+6
lib/python3.12/site-packages/accelerate-1.7.0.dist-info/top_level.txtAdded+1
lib/python3.12/site-packages/accelerate/__init__.pyAdded+50
lib/python3.12/site-packages/accelerate/accelerator.pyAdded
lib/python3.12/site-packages/accelerate/big_modeling.pyAdded+749
lib/python3.12/site-packages/accelerate/checkpointing.pyAdded+319
lib/python3.12/site-packages/accelerate/commands/__init__.pyAdded+13
lib/python3.12/site-packages/accelerate/commands/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/accelerate/commands/__pycache__/accelerate_cli.cpython-312.pycAdded
lib/python3.12/site-packages/accelerate/commands/__pycache__/env.cpython-312.pycAdded
lib/python3.12/site-packages/accelerate/commands/__pycache__/estimate.cpython-312.pycAdded
lib/python3.12/site-packages/accelerate/commands/__pycache__/launch.cpython-312.pycAdded
lib/python3.12/site-packages/accelerate/commands/__pycache__/merge.cpython-312.pycAdded
lib/python3.12/site-packages/accelerate/commands/__pycache__/test.cpython-312.pycAdded
lib/python3.12/site-packages/accelerate/commands/__pycache__/to_fsdp2.cpython-312.pycAdded
lib/python3.12/site-packages/accelerate/commands/__pycache__/tpu.cpython-312.pycAdded
lib/python3.12/site-packages/accelerate/commands/__pycache__/utils.cpython-312.pycAdded
lib/python3.12/site-packages/accelerate/commands/accelerate_cli.pyAdded+54
lib/python3.12/site-packages/accelerate/commands/config/__init__.pyAdded+52
lib/python3.12/site-packages/accelerate/commands/config/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/accelerate/commands/config/__pycache__/cluster.cpython-312.pycAdded
lib/python3.12/site-packages/accelerate/commands/config/__pycache__/config.cpython-312.pycAdded
lib/python3.12/site-packages/accelerate/commands/config/__pycache__/config_args.cpython-312.pycAdded
lib/python3.12/site-packages/accelerate/commands/config/__pycache__/config_utils.cpython-312.pycAdded
lib/python3.12/site-packages/accelerate/commands/config/__pycache__/default.cpython-312.pycAdded
lib/python3.12/site-packages/accelerate/commands/config/__pycache__/sagemaker.cpython-312.pycAdded
lib/python3.12/site-packages/accelerate/commands/config/__pycache__/update.cpython-312.pycAdded
lib/python3.12/site-packages/accelerate/commands/config/cluster.pyAdded+869
lib/python3.12/site-packages/accelerate/commands/config/config.pyAdded+89
lib/python3.12/site-packages/accelerate/commands/config/config_args.pyAdded+252
lib/python3.12/site-packages/accelerate/commands/config/config_utils.pyAdded+122
lib/python3.12/site-packages/accelerate/commands/config/default.pyAdded+163
lib/python3.12/site-packages/accelerate/commands/config/sagemaker.pyAdded+274
lib/python3.12/site-packages/accelerate/commands/config/update.pyAdded+63
lib/python3.12/site-packages/accelerate/commands/env.pyAdded+131
lib/python3.12/site-packages/accelerate/commands/estimate.pyAdded+312
lib/python3.12/site-packages/accelerate/commands/launch.pyAdded+1208
lib/python3.12/site-packages/accelerate/commands/menu/__init__.pyAdded+14
lib/python3.12/site-packages/accelerate/commands/menu/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/accelerate/commands/menu/__pycache__/cursor.cpython-312.pycAdded
lib/python3.12/site-packages/accelerate/commands/menu/__pycache__/helpers.cpython-312.pycAdded
lib/python3.12/site-packages/accelerate/commands/menu/__pycache__/input.cpython-312.pycAdded
lib/python3.12/site-packages/accelerate/commands/menu/__pycache__/keymap.cpython-312.pycAdded
lib/python3.12/site-packages/accelerate/commands/menu/__pycache__/selection_menu.cpython-312.pycAdded