AdithyaSK HF Staff commited on
Commit
c5fcacc
·
verified ·
1 Parent(s): 6fb8e66

Stage Harbor release files 70501-71000

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/tasksmith-b1dd32dfa88b/tests/source/pyproject.toml +43 -0
  2. tasks/tasksmith-b1dd32dfa88b/tests/source/setup.py +127 -0
  3. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/__init__.py +51 -0
  4. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/accelerator.py +0 -0
  5. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/big_modeling.py +789 -0
  6. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/checkpointing.py +330 -0
  7. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/__init__.py +13 -0
  8. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/accelerate_cli.py +54 -0
  9. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/__init__.py +52 -0
  10. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/cluster.py +917 -0
  11. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/config.py +89 -0
  12. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/config_args.py +256 -0
  13. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/config_utils.py +122 -0
  14. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/default.py +163 -0
  15. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/sagemaker.py +274 -0
  16. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/update.py +63 -0
  17. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/env.py +131 -0
  18. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/estimate.py +312 -0
  19. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/launch.py +1258 -0
  20. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/menu/__init__.py +14 -0
  21. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/menu/cursor.py +65 -0
  22. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/menu/helpers.py +59 -0
  23. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/menu/input.py +84 -0
  24. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/menu/keymap.py +133 -0
  25. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/menu/selection_menu.py +144 -0
  26. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/merge.py +69 -0
  27. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/test.py +65 -0
  28. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/to_fsdp2.py +172 -0
  29. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/tpu.py +157 -0
  30. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/utils.py +123 -0
  31. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/data_loader.py +1451 -0
  32. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/hooks.py +765 -0
  33. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/inference.py +184 -0
  34. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/launchers.py +306 -0
  35. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/local_sgd.py +106 -0
  36. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/logging.py +125 -0
  37. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/memory_utils.py +22 -0
  38. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/optimizer.py +213 -0
  39. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/parallelism_config.py +289 -0
  40. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/scheduler.py +98 -0
  41. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/state.py +1369 -0
  42. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/__init__.py +65 -0
  43. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/examples.py +145 -0
  44. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/__init__.py +13 -0
  45. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/__init__.py +13 -0
  46. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/test_checkpointing.py +269 -0
  47. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/test_ds_multiple_model.py +332 -0
  48. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/test_metrics.py +307 -0
  49. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/test_peak_memory_usage.py +314 -0
  50. tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/test_performance.py +299 -0
tasks/tasksmith-b1dd32dfa88b/tests/source/pyproject.toml ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [tool.ruff]
2
+ line-length = 119
3
+ target-version = "py39"
4
+
5
+ [tool.ruff.lint]
6
+ preview = true
7
+ extend-select = [
8
+ "B009", # static getattr
9
+ "B010", # static setattr
10
+ "CPY", # Copyright
11
+ "E", # PEP8 errors
12
+ "F", # PEP8 formatting
13
+ "I", # Import sorting
14
+ "TID251", # Banned API
15
+ "UP", # Pyupgrade
16
+ "W", # PEP8 warnings
17
+ ]
18
+ ignore = [
19
+ "E501", # Line length (handled by ruff-format)
20
+ "E741", # Ambiguous variable name
21
+ "W605", # Invalid escape sequence
22
+ "UP007", # X | Y type annotations
23
+ ]
24
+
25
+ [tool.ruff.lint.per-file-ignores]
26
+ "__init__.py" = [
27
+ "F401", # Ignore seemingly unused imports (they're meant for re-export)
28
+ ]
29
+ "manim_animations/*" = ["ALL"]
30
+
31
+ [tool.ruff.lint.isort]
32
+ lines-after-imports = 2
33
+ known-first-party = ["accelerate"]
34
+
35
+ [tool.ruff.format]
36
+ exclude = [
37
+ "manim_animations/*"
38
+ ]
39
+
40
+ [tool.ruff.lint.flake8-tidy-imports.banned-api]
41
+ "os.getenv".msg = "Use os.environ instead"
42
+ "os.putenv".msg = "Use os.environ instead"
43
+ "os.unsetenv".msg = "Use os.environ instead"
tasks/tasksmith-b1dd32dfa88b/tests/source/setup.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from setuptools import find_packages, setup
16
+
17
+
18
+ extras = {}
19
+ extras["quality"] = [
20
+ "black ~= 23.1", # hf-doc-builder has a hidden dependency on `black`
21
+ "hf-doc-builder >= 0.3.0",
22
+ "ruff ~= 0.11.2",
23
+ ]
24
+ extras["docs"] = []
25
+ extras["test_prod"] = ["pytest>=7.2.0,<=8.0.0", "pytest-xdist", "pytest-subtests", "parameterized", "pytest-order"]
26
+ extras["test_dev"] = [
27
+ "datasets",
28
+ "diffusers",
29
+ "evaluate",
30
+ "torchdata>=0.8.0",
31
+ "torchpippy>=0.2.0",
32
+ "transformers",
33
+ "scipy",
34
+ "scikit-learn",
35
+ "tqdm",
36
+ "bitsandbytes",
37
+ "timm",
38
+ ]
39
+ extras["testing"] = extras["test_prod"] + extras["test_dev"]
40
+ extras["deepspeed"] = ["deepspeed"]
41
+ extras["rich"] = ["rich"]
42
+
43
+ extras["test_fp8"] = ["torchao"] # note: TE for now needs to be done via pulling down the docker image directly
44
+ extras["test_trackers"] = [
45
+ "wandb",
46
+ "comet-ml",
47
+ "tensorboard",
48
+ "dvclive",
49
+ "mlflow",
50
+ "matplotlib",
51
+ "swanlab",
52
+ "trackio",
53
+ ]
54
+ extras["dev"] = extras["quality"] + extras["testing"] + extras["rich"]
55
+
56
+ extras["sagemaker"] = [
57
+ "sagemaker", # boto3 is a required package in sagemaker
58
+ ]
59
+
60
+ setup(
61
+ name="accelerate",
62
+ version="1.10.0.dev0",
63
+ description="Accelerate",
64
+ long_description=open("README.md", encoding="utf-8").read(),
65
+ long_description_content_type="text/markdown",
66
+ keywords="deep learning",
67
+ license="Apache",
68
+ author="The HuggingFace team",
69
+ author_email="zach.mueller@huggingface.co",
70
+ url="https://github.com/huggingface/accelerate",
71
+ package_dir={"": "src"},
72
+ packages=find_packages("src"),
73
+ entry_points={
74
+ "console_scripts": [
75
+ "accelerate=accelerate.commands.accelerate_cli:main",
76
+ "accelerate-config=accelerate.commands.config:main",
77
+ "accelerate-estimate-memory=accelerate.commands.estimate:main",
78
+ "accelerate-launch=accelerate.commands.launch:main",
79
+ "accelerate-merge-weights=accelerate.commands.merge:main",
80
+ ]
81
+ },
82
+ python_requires=">=3.9.0",
83
+ install_requires=[
84
+ "numpy>=1.17,<3.0.0",
85
+ "packaging>=20.0",
86
+ "psutil",
87
+ "pyyaml",
88
+ "torch>=2.0.0",
89
+ "huggingface_hub>=0.21.0",
90
+ "safetensors>=0.4.3",
91
+ ],
92
+ extras_require=extras,
93
+ classifiers=[
94
+ "Development Status :: 5 - Production/Stable",
95
+ "Intended Audience :: Developers",
96
+ "Intended Audience :: Education",
97
+ "Intended Audience :: Science/Research",
98
+ "License :: OSI Approved :: Apache Software License",
99
+ "Operating System :: OS Independent",
100
+ "Programming Language :: Python :: 3",
101
+ "Programming Language :: Python :: 3.9",
102
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
103
+ ],
104
+ )
105
+
106
+ # Release checklist
107
+ # 1. Checkout the release branch (for a patch the current release branch, for a new minor version, create one):
108
+ # git checkout -b vXX.xx-release
109
+ # The -b is only necessary for creation (so remove it when doing a patch)
110
+ # 2. Change the version in __init__.py and setup.py to the proper value.
111
+ # 3. Commit these changes with the message: "Release: v<VERSION>"
112
+ # 4. Add a tag in git to mark the release:
113
+ # git tag v<VERSION> -m 'Adds tag v<VERSION> for pypi'
114
+ # Push the tag and release commit to git: git push --tags origin vXX.xx-release
115
+ # 5. Run the following commands in the top-level directory:
116
+ # make prepare_release
117
+ # 6. Upload the package to the pypi test server first:
118
+ # make target=testpypi upload_release
119
+ # 7. Check that you can install it in a virtualenv by running:
120
+ # make install_test_release
121
+ # accelerate env
122
+ # accelerate test
123
+ # 8. Upload the final version to actual pypi:
124
+ # make target=pypi upload_release
125
+ # 9. Add release notes to the tag in github once everything is looking hunky-dory.
126
+ # 10. Go back to the main branch and update the version in __init__.py, setup.py to the new version ".dev" and push to
127
+ # main.
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/__init__.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ __version__ = "1.10.0.dev0"
15
+
16
+ from .accelerator import Accelerator
17
+ from .big_modeling import (
18
+ cpu_offload,
19
+ cpu_offload_with_hook,
20
+ disk_offload,
21
+ dispatch_model,
22
+ init_empty_weights,
23
+ init_on_device,
24
+ load_checkpoint_and_dispatch,
25
+ )
26
+ from .data_loader import skip_first_batches
27
+ from .inference import prepare_pippy
28
+ from .launchers import debug_launcher, notebook_launcher
29
+ from .parallelism_config import ParallelismConfig
30
+ from .state import PartialState
31
+ from .utils import (
32
+ AutocastKwargs,
33
+ DataLoaderConfiguration,
34
+ DDPCommunicationHookType,
35
+ DeepSpeedPlugin,
36
+ DistributedDataParallelKwargs,
37
+ DistributedType,
38
+ FullyShardedDataParallelPlugin,
39
+ GradScalerKwargs,
40
+ InitProcessGroupKwargs,
41
+ ProfileKwargs,
42
+ find_executable_batch_size,
43
+ infer_auto_device_map,
44
+ is_rich_available,
45
+ load_checkpoint_in_model,
46
+ synchronize_rng_states,
47
+ )
48
+
49
+
50
+ if is_rich_available():
51
+ from .utils import rich
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/accelerator.py ADDED
The diff for this file is too large to render. See raw diff
 
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/big_modeling.py ADDED
@@ -0,0 +1,789 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import logging
16
+ import os
17
+ import re
18
+ from contextlib import contextmanager
19
+ from functools import wraps
20
+ from typing import Optional, Union
21
+
22
+ import torch
23
+ import torch.nn as nn
24
+
25
+ from .hooks import (
26
+ AlignDevicesHook,
27
+ CpuOffload,
28
+ LayerwiseCastingHook,
29
+ UserCpuOffloadHook,
30
+ add_hook_to_module,
31
+ attach_align_device_hook,
32
+ attach_align_device_hook_on_blocks,
33
+ )
34
+ from .utils import (
35
+ OffloadedWeightsLoader,
36
+ check_cuda_p2p_ib_support,
37
+ check_device_map,
38
+ extract_submodules_state_dict,
39
+ find_tied_parameters,
40
+ get_balanced_memory,
41
+ infer_auto_device_map,
42
+ is_bnb_available,
43
+ is_mlu_available,
44
+ is_musa_available,
45
+ is_npu_available,
46
+ is_sdaa_available,
47
+ is_xpu_available,
48
+ load_checkpoint_in_model,
49
+ offload_state_dict,
50
+ parse_flag_from_env,
51
+ retie_parameters,
52
+ )
53
+ from .utils.constants import SUPPORTED_PYTORCH_LAYERS_FOR_UPCASTING
54
+ from .utils.other import recursive_getattr
55
+
56
+
57
+ logger = logging.getLogger(__name__)
58
+
59
+
60
+ @contextmanager
61
+ def init_empty_weights(include_buffers: bool = None):
62
+ """
63
+ A context manager under which models are initialized with all parameters on the meta device, therefore creating an
64
+ empty model. Useful when just initializing the model would blow the available RAM.
65
+
66
+ Args:
67
+ include_buffers (`bool`, *optional*):
68
+ Whether or not to also put all buffers on the meta device while initializing.
69
+
70
+ Example:
71
+
72
+ ```python
73
+ import torch.nn as nn
74
+ from accelerate import init_empty_weights
75
+
76
+ # Initialize a model with 100 billions parameters in no time and without using any RAM.
77
+ with init_empty_weights():
78
+ tst = nn.Sequential(*[nn.Linear(10000, 10000) for _ in range(1000)])
79
+ ```
80
+
81
+ <Tip warning={true}>
82
+
83
+ Any model created under this context manager has no weights. As such you can't do something like
84
+ `model.to(some_device)` with it. To load weights inside your empty model, see [`load_checkpoint_and_dispatch`].
85
+ Make sure to overwrite the default device_map param for [`load_checkpoint_and_dispatch`], otherwise dispatch is not
86
+ called.
87
+
88
+ </Tip>
89
+ """
90
+ if include_buffers is None:
91
+ include_buffers = parse_flag_from_env("ACCELERATE_INIT_INCLUDE_BUFFERS", False)
92
+ with init_on_device(torch.device("meta"), include_buffers=include_buffers) as f:
93
+ yield f
94
+
95
+
96
+ @contextmanager
97
+ def init_on_device(device: torch.device, include_buffers: bool = None):
98
+ """
99
+ A context manager under which models are initialized with all parameters on the specified device.
100
+
101
+ Args:
102
+ device (`torch.device`):
103
+ Device to initialize all parameters on.
104
+ include_buffers (`bool`, *optional*):
105
+ Whether or not to also put all buffers on the meta device while initializing.
106
+
107
+ Example:
108
+
109
+ ```python
110
+ import torch.nn as nn
111
+ from accelerate import init_on_device
112
+
113
+ with init_on_device(device=torch.device("cuda")):
114
+ tst = nn.Linear(100, 100) # on `cuda` device
115
+ ```
116
+ """
117
+ if include_buffers is None:
118
+ include_buffers = parse_flag_from_env("ACCELERATE_INIT_INCLUDE_BUFFERS", False)
119
+
120
+ if include_buffers:
121
+ with device:
122
+ yield
123
+ return
124
+
125
+ old_register_parameter = nn.Module.register_parameter
126
+ if include_buffers:
127
+ old_register_buffer = nn.Module.register_buffer
128
+
129
+ def register_empty_parameter(module, name, param):
130
+ old_register_parameter(module, name, param)
131
+ if param is not None:
132
+ param_cls = type(module._parameters[name])
133
+ kwargs = module._parameters[name].__dict__
134
+ kwargs["requires_grad"] = param.requires_grad
135
+ module._parameters[name] = param_cls(module._parameters[name].to(device), **kwargs)
136
+
137
+ def register_empty_buffer(module, name, buffer, persistent=True):
138
+ old_register_buffer(module, name, buffer, persistent=persistent)
139
+ if buffer is not None:
140
+ module._buffers[name] = module._buffers[name].to(device)
141
+
142
+ # Patch tensor creation
143
+ if include_buffers:
144
+ tensor_constructors_to_patch = {
145
+ torch_function_name: getattr(torch, torch_function_name)
146
+ for torch_function_name in ["empty", "zeros", "ones", "full"]
147
+ }
148
+ else:
149
+ tensor_constructors_to_patch = {}
150
+
151
+ def patch_tensor_constructor(fn):
152
+ def wrapper(*args, **kwargs):
153
+ kwargs["device"] = device
154
+ return fn(*args, **kwargs)
155
+
156
+ return wrapper
157
+
158
+ try:
159
+ nn.Module.register_parameter = register_empty_parameter
160
+ if include_buffers:
161
+ nn.Module.register_buffer = register_empty_buffer
162
+ for torch_function_name in tensor_constructors_to_patch.keys():
163
+ setattr(torch, torch_function_name, patch_tensor_constructor(getattr(torch, torch_function_name)))
164
+ yield
165
+ finally:
166
+ nn.Module.register_parameter = old_register_parameter
167
+ if include_buffers:
168
+ nn.Module.register_buffer = old_register_buffer
169
+ for torch_function_name, old_torch_function in tensor_constructors_to_patch.items():
170
+ setattr(torch, torch_function_name, old_torch_function)
171
+
172
+
173
+ def cpu_offload(
174
+ model: nn.Module,
175
+ execution_device: Optional[torch.device] = None,
176
+ offload_buffers: bool = False,
177
+ state_dict: Optional[dict[str, torch.Tensor]] = None,
178
+ preload_module_classes: Optional[list[str]] = None,
179
+ ):
180
+ """
181
+ Activates full CPU offload for a model. As a result, all parameters of the model will be offloaded and only one
182
+ copy of the state dict of the model will be kept. During the forward pass, parameters will be extracted from that
183
+ state dict and put on the execution device passed as they are needed, then offloaded again.
184
+
185
+ Args:
186
+ model (`torch.nn.Module`):
187
+ The model to offload.
188
+ execution_device (`torch.device`, *optional*):
189
+ The device on which the forward pass of the model will be executed (should be a GPU). Will default to the
190
+ model first parameter device.
191
+ offload_buffers (`bool`, *optional*, defaults to `False`):
192
+ Whether or not to offload the buffers with the model parameters.
193
+ state_dict (`Dict[str, torch.Tensor]`, *optional*):
194
+ The state dict of the model that will be kept on CPU.
195
+ preload_module_classes (`List[str]`, *optional*):
196
+ A list of classes whose instances should load all their weights (even in the submodules) at the beginning
197
+ of the forward. This should only be used for classes that have submodules which are registered but not
198
+ called directly during the forward, for instance if a `dense` linear layer is registered, but at forward,
199
+ `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly.
200
+ """
201
+ if execution_device is None:
202
+ execution_device = next(iter(model.parameters())).device
203
+ if state_dict is None:
204
+ state_dict = {n: p.to("cpu") for n, p in model.state_dict().items()}
205
+
206
+ add_hook_to_module(model, AlignDevicesHook(io_same_device=True), append=True)
207
+ attach_align_device_hook(
208
+ model,
209
+ execution_device=execution_device,
210
+ offload=True,
211
+ offload_buffers=offload_buffers,
212
+ weights_map=state_dict,
213
+ preload_module_classes=preload_module_classes,
214
+ )
215
+
216
+ return model
217
+
218
+
219
+ def cpu_offload_with_hook(
220
+ model: torch.nn.Module,
221
+ execution_device: Optional[Union[int, str, torch.device]] = None,
222
+ prev_module_hook: Optional[UserCpuOffloadHook] = None,
223
+ ):
224
+ """
225
+ Offloads a model on the CPU and puts it back to an execution device when executed. The difference with
226
+ [`cpu_offload`] is that the model stays on the execution device after the forward and is only offloaded again when
227
+ the `offload` method of the returned `hook` is called. Useful for pipelines running a model in a loop.
228
+
229
+ Args:
230
+ model (`torch.nn.Module`):
231
+ The model to offload.
232
+ execution_device(`str`, `int` or `torch.device`, *optional*):
233
+ The device on which the model should be executed. Will default to the MPS device if it's available, then
234
+ GPU 0 if there is a GPU, and finally to the CPU.
235
+ prev_module_hook (`UserCpuOffloadHook`, *optional*):
236
+ The hook sent back by this function for a previous model in the pipeline you are running. If passed, its
237
+ offload method will be called just before the forward of the model to which this hook is attached.
238
+
239
+ Example:
240
+
241
+ ```py
242
+ model_1, hook_1 = cpu_offload_with_hook(model_1, cuda_device)
243
+ model_2, hook_2 = cpu_offload_with_hook(model_2, cuda_device, prev_module_hook=hook_1)
244
+ model_3, hook_3 = cpu_offload_with_hook(model_3, cuda_device, prev_module_hook=hook_2)
245
+
246
+ hid_1 = model_1(input)
247
+ for i in range(50):
248
+ # model1 is offloaded on the CPU at the first iteration, model 2 stays on the GPU for this whole loop.
249
+ hid_2 = model_2(hid_1)
250
+ # model2 is offloaded to the CPU just before this forward.
251
+ hid_3 = model_3(hid_3)
252
+
253
+ # For model3, you need to manually call the hook offload method.
254
+ hook_3.offload()
255
+ ```
256
+ """
257
+ hook = CpuOffload(execution_device=execution_device, prev_module_hook=prev_module_hook)
258
+ add_hook_to_module(model, hook, append=True)
259
+ user_hook = UserCpuOffloadHook(model, hook)
260
+ return model, user_hook
261
+
262
+
263
+ def disk_offload(
264
+ model: nn.Module,
265
+ offload_dir: Union[str, os.PathLike],
266
+ execution_device: Optional[torch.device] = None,
267
+ offload_buffers: bool = False,
268
+ preload_module_classes: Optional[list[str]] = None,
269
+ ):
270
+ """
271
+ Activates full disk offload for a model. As a result, all parameters of the model will be offloaded as
272
+ memory-mapped array in a given folder. During the forward pass, parameters will be accessed from that folder and
273
+ put on the execution device passed as they are needed, then offloaded again.
274
+
275
+ Args:
276
+ model (`torch.nn.Module`): The model to offload.
277
+ offload_dir (`str` or `os.PathLike`):
278
+ The folder in which to offload the model weights (or where the model weights are already offloaded).
279
+ execution_device (`torch.device`, *optional*):
280
+ The device on which the forward pass of the model will be executed (should be a GPU). Will default to the
281
+ model's first parameter device.
282
+ offload_buffers (`bool`, *optional*, defaults to `False`):
283
+ Whether or not to offload the buffers with the model parameters.
284
+ preload_module_classes (`List[str]`, *optional*):
285
+ A list of classes whose instances should load all their weights (even in the submodules) at the beginning
286
+ of the forward. This should only be used for classes that have submodules which are registered but not
287
+ called directly during the forward, for instance if a `dense` linear layer is registered, but at forward,
288
+ `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly.
289
+ """
290
+ if not os.path.isdir(offload_dir) or not os.path.isfile(os.path.join(offload_dir, "index.json")):
291
+ offload_state_dict(offload_dir, model.state_dict())
292
+ if execution_device is None:
293
+ execution_device = next(iter(model.parameters())).device
294
+ weights_map = OffloadedWeightsLoader(save_folder=offload_dir)
295
+
296
+ add_hook_to_module(model, AlignDevicesHook(io_same_device=True), append=True)
297
+ attach_align_device_hook(
298
+ model,
299
+ execution_device=execution_device,
300
+ offload=True,
301
+ offload_buffers=offload_buffers,
302
+ weights_map=weights_map,
303
+ preload_module_classes=preload_module_classes,
304
+ )
305
+
306
+ return model
307
+
308
+
309
+ def dispatch_model(
310
+ model: nn.Module,
311
+ device_map: dict[str, Union[str, int, torch.device]],
312
+ main_device: Optional[torch.device] = None,
313
+ state_dict: Optional[dict[str, torch.Tensor]] = None,
314
+ offload_dir: Optional[Union[str, os.PathLike]] = None,
315
+ offload_index: Optional[dict[str, str]] = None,
316
+ offload_buffers: bool = False,
317
+ skip_keys: Optional[Union[str, list[str]]] = None,
318
+ preload_module_classes: Optional[list[str]] = None,
319
+ force_hooks: bool = False,
320
+ ):
321
+ """
322
+ Dispatches a model according to a given device map. Layers of the model might be spread across GPUs, offloaded on
323
+ the CPU or even the disk.
324
+
325
+ Args:
326
+ model (`torch.nn.Module`):
327
+ The model to dispatch.
328
+ device_map (`Dict[str, Union[str, int, torch.device]]`):
329
+ A dictionary mapping module names in the models `state_dict` to the device they should go to. Note that
330
+ `"disk"` is accepted even if it's not a proper value for `torch.device`.
331
+ main_device (`str`, `int` or `torch.device`, *optional*):
332
+ The main execution device. Will default to the first device in the `device_map` different from `"cpu"` or
333
+ `"disk"`.
334
+ state_dict (`Dict[str, torch.Tensor]`, *optional*):
335
+ The state dict of the part of the model that will be kept on CPU.
336
+ offload_dir (`str` or `os.PathLike`):
337
+ The folder in which to offload the model weights (or where the model weights are already offloaded).
338
+ offload_index (`Dict`, *optional*):
339
+ A dictionary from weight name to their information (`dtype`/ `shape` or safetensors filename). Will default
340
+ to the index saved in `save_folder`.
341
+ offload_buffers (`bool`, *optional*, defaults to `False`):
342
+ Whether or not to offload the buffers with the model parameters.
343
+ skip_keys (`str` or `List[str]`, *optional*):
344
+ A list of keys to ignore when moving inputs or outputs between devices.
345
+ preload_module_classes (`List[str]`, *optional*):
346
+ A list of classes whose instances should load all their weights (even in the submodules) at the beginning
347
+ of the forward. This should only be used for classes that have submodules which are registered but not
348
+ called directly during the forward, for instance if a `dense` linear layer is registered, but at forward,
349
+ `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly.
350
+ force_hooks (`bool`, *optional*, defaults to `False`):
351
+ Whether or not to force device hooks to be attached to the model even if all layers are dispatched to a
352
+ single device.
353
+ """
354
+ # Error early if the device map is incomplete.
355
+ check_device_map(model, device_map)
356
+
357
+ # We need to force hook for quantized model that can't be moved with to()
358
+ if getattr(model, "quantization_method", "bitsandbytes") == "bitsandbytes":
359
+ # since bnb 0.43.2, we can move 4-bit model
360
+ if getattr(model, "is_loaded_in_8bit", False) or (
361
+ getattr(model, "is_loaded_in_4bit", False) and not is_bnb_available(min_version="0.43.2")
362
+ ):
363
+ force_hooks = True
364
+
365
+ # We attach hooks if the device_map has at least 2 different devices or if
366
+ # force_hooks is set to `True`. Otherwise, the model in already loaded
367
+ # in the unique device and the user can decide where to dispatch the model.
368
+ # If the model is quantized, we always force-dispatch the model
369
+ if (len(set(device_map.values())) > 1) or force_hooks:
370
+ if main_device is None:
371
+ if set(device_map.values()) == {"cpu"} or set(device_map.values()) == {"cpu", "disk"}:
372
+ main_device = "cpu"
373
+ else:
374
+ main_device = [d for d in device_map.values() if d not in ["cpu", "disk"]][0]
375
+
376
+ if main_device != "cpu":
377
+ cpu_modules = [name for name, device in device_map.items() if device == "cpu"]
378
+ if state_dict is None and len(cpu_modules) > 0:
379
+ state_dict = extract_submodules_state_dict(model.state_dict(), cpu_modules)
380
+
381
+ disk_modules = [name for name, device in device_map.items() if device == "disk"]
382
+ if offload_dir is None and offload_index is None and len(disk_modules) > 0:
383
+ raise ValueError(
384
+ "We need an `offload_dir` to dispatch this model according to this `device_map`, the following submodules "
385
+ f"need to be offloaded: {', '.join(disk_modules)}."
386
+ )
387
+ if (
388
+ len(disk_modules) > 0
389
+ and offload_index is None
390
+ and (not os.path.isdir(offload_dir) or not os.path.isfile(os.path.join(offload_dir, "index.json")))
391
+ ):
392
+ disk_state_dict = extract_submodules_state_dict(model.state_dict(), disk_modules)
393
+ offload_state_dict(offload_dir, disk_state_dict)
394
+
395
+ execution_device = {
396
+ name: main_device if device in ["cpu", "disk"] else device for name, device in device_map.items()
397
+ }
398
+ execution_device[""] = main_device
399
+ offloaded_devices = ["disk"] if main_device == "cpu" or main_device == "mps" else ["cpu", "disk"]
400
+ offload = {name: device in offloaded_devices for name, device in device_map.items()}
401
+ save_folder = offload_dir if len(disk_modules) > 0 else None
402
+ if state_dict is not None or save_folder is not None or offload_index is not None:
403
+ device = main_device if offload_index is not None else None
404
+ weights_map = OffloadedWeightsLoader(
405
+ state_dict=state_dict, save_folder=save_folder, index=offload_index, device=device
406
+ )
407
+ else:
408
+ weights_map = None
409
+
410
+ # When dispatching the model's parameters to the devices specified in device_map, we want to avoid allocating memory several times for the
411
+ # tied parameters. The dictionary tied_params_map keeps track of the already allocated data for a given tied parameter (represented by its
412
+ # original pointer) on each devices.
413
+ tied_params = find_tied_parameters(model)
414
+
415
+ tied_params_map = {}
416
+ for group in tied_params:
417
+ for param_name in group:
418
+ # data_ptr() is enough here, as `find_tied_parameters` finds tied params simply by comparing `param1 is param2`, so we don't need
419
+ # to care about views of tensors through storage_offset.
420
+ data_ptr = recursive_getattr(model, param_name).data_ptr()
421
+ tied_params_map[data_ptr] = {}
422
+
423
+ # Note: To handle the disk offloading case, we can not simply use weights_map[param_name].data_ptr() as the reference pointer,
424
+ # as we have no guarantee that safetensors' `file.get_tensor()` will always give the same pointer.
425
+
426
+ attach_align_device_hook_on_blocks(
427
+ model,
428
+ execution_device=execution_device,
429
+ offload=offload,
430
+ offload_buffers=offload_buffers,
431
+ weights_map=weights_map,
432
+ skip_keys=skip_keys,
433
+ preload_module_classes=preload_module_classes,
434
+ tied_params_map=tied_params_map,
435
+ )
436
+
437
+ # warn if there is any params on the meta device
438
+ offloaded_devices_str = " and ".join(
439
+ [device for device in set(device_map.values()) if device in ("cpu", "disk")]
440
+ )
441
+ if len(offloaded_devices_str) > 0:
442
+ logger.warning(
443
+ f"Some parameters are on the meta device because they were offloaded to the {offloaded_devices_str}."
444
+ )
445
+
446
+ # Attaching the hook may break tied weights, so we retie them
447
+ retie_parameters(model, tied_params)
448
+
449
+ # add warning to cuda and to method
450
+ def add_warning(fn, model):
451
+ @wraps(fn)
452
+ def wrapper(*args, **kwargs):
453
+ warning_msg = "You shouldn't move a model that is dispatched using accelerate hooks."
454
+ if str(fn.__name__) == "to":
455
+ to_device = torch._C._nn._parse_to(*args, **kwargs)[0]
456
+ if to_device is not None:
457
+ logger.warning(warning_msg)
458
+ else:
459
+ logger.warning(warning_msg)
460
+ for param in model.parameters():
461
+ if param.device == torch.device("meta"):
462
+ raise RuntimeError("You can't move a model that has some modules offloaded to cpu or disk.")
463
+ return fn(*args, **kwargs)
464
+
465
+ return wrapper
466
+
467
+ # Make sure to update _accelerate_added_attributes in hooks.py if you add any hook
468
+ model.to = add_warning(model.to, model)
469
+ if is_npu_available():
470
+ model.npu = add_warning(model.npu, model)
471
+ elif is_mlu_available():
472
+ model.mlu = add_warning(model.mlu, model)
473
+ elif is_sdaa_available():
474
+ model.sdaa = add_warning(model.sdaa, model)
475
+ elif is_musa_available():
476
+ model.musa = add_warning(model.musa, model)
477
+ elif is_xpu_available():
478
+ model.xpu = add_warning(model.xpu, model)
479
+ else:
480
+ model.cuda = add_warning(model.cuda, model)
481
+
482
+ # Check if we are using multi-gpus with RTX 4000 series
483
+ use_multi_gpu = len([device for device in set(device_map.values()) if device not in ("cpu", "disk")]) > 1
484
+ if use_multi_gpu and not check_cuda_p2p_ib_support():
485
+ logger.warning(
486
+ "We've detected an older driver with an RTX 4000 series GPU. These drivers have issues with P2P. "
487
+ "This can affect the multi-gpu inference when using accelerate device_map."
488
+ "Please make sure to update your driver to the latest version which resolves this."
489
+ )
490
+ else:
491
+ device = list(device_map.values())[0]
492
+ # `torch.Tensor.to(<int num>)` is not supported by `torch_npu` (see this [issue](https://github.com/Ascend/pytorch/issues/16)).
493
+ if is_npu_available() and isinstance(device, int):
494
+ device = f"npu:{device}"
495
+ elif is_mlu_available() and isinstance(device, int):
496
+ device = f"mlu:{device}"
497
+ elif is_sdaa_available() and isinstance(device, int):
498
+ device = f"sdaa:{device}"
499
+ elif is_musa_available() and isinstance(device, int):
500
+ device = f"musa:{device}"
501
+ if device != "disk":
502
+ model.to(device)
503
+ else:
504
+ raise ValueError(
505
+ "You are trying to offload the whole model to the disk. Please use the `disk_offload` function instead."
506
+ )
507
+ # Convert OrderedDict back to dict for easier usage
508
+ model.hf_device_map = dict(device_map)
509
+ return model
510
+
511
+
512
+ def load_checkpoint_and_dispatch(
513
+ model: nn.Module,
514
+ checkpoint: Union[str, os.PathLike],
515
+ device_map: Optional[Union[str, dict[str, Union[int, str, torch.device]]]] = None,
516
+ max_memory: Optional[dict[Union[int, str], Union[int, str]]] = None,
517
+ no_split_module_classes: Optional[list[str]] = None,
518
+ offload_folder: Optional[Union[str, os.PathLike]] = None,
519
+ offload_buffers: bool = False,
520
+ dtype: Optional[Union[str, torch.dtype]] = None,
521
+ offload_state_dict: Optional[bool] = None,
522
+ skip_keys: Optional[Union[str, list[str]]] = None,
523
+ preload_module_classes: Optional[list[str]] = None,
524
+ force_hooks: bool = False,
525
+ strict: bool = False,
526
+ full_state_dict: bool = True,
527
+ broadcast_from_rank0: bool = False,
528
+ ):
529
+ """
530
+ Loads a (potentially sharded) checkpoint inside a model, potentially sending weights to a given device as they are
531
+ loaded and adds the various hooks that will make this model run properly (even if split across devices).
532
+
533
+ Args:
534
+ model (`torch.nn.Module`): The model in which we want to load a checkpoint.
535
+ checkpoint (`str` or `os.PathLike`):
536
+ The folder checkpoint to load. It can be:
537
+ - a path to a file containing a whole model state dict
538
+ - a path to a `.json` file containing the index to a sharded checkpoint
539
+ - a path to a folder containing a unique `.index.json` file and the shards of a checkpoint.
540
+ device_map (`Dict[str, Union[int, str, torch.device]]`, *optional*):
541
+ A map that specifies where each submodule should go. It doesn't need to be refined to each parameter/buffer
542
+ name, once a given module name is inside, every submodule of it will be sent to the same device.
543
+
544
+ To have Accelerate compute the most optimized `device_map` automatically, set `device_map="auto"`. For more
545
+ information about each option see [here](../concept_guides/big_model_inference#designing-a-device-map).
546
+ Defaults to None, which means [`dispatch_model`] will not be called.
547
+ max_memory (`Dict`, *optional*):
548
+ A dictionary device identifier to maximum memory. Will default to the maximum memory available for each GPU
549
+ and the available CPU RAM if unset.
550
+ no_split_module_classes (`List[str]`, *optional*):
551
+ A list of layer class names that should never be split across device (for instance any layer that has a
552
+ residual connection).
553
+ offload_folder (`str` or `os.PathLike`, *optional*):
554
+ If the `device_map` contains any value `"disk"`, the folder where we will offload weights.
555
+ offload_buffers (`bool`, *optional*, defaults to `False`):
556
+ In the layers that are offloaded on the CPU or the hard drive, whether or not to offload the buffers as
557
+ well as the parameters.
558
+ dtype (`str` or `torch.dtype`, *optional*):
559
+ If provided, the weights will be converted to that type when loaded.
560
+ offload_state_dict (`bool`, *optional*):
561
+ If `True`, will temporarily offload the CPU state dict on the hard drive to avoid getting out of CPU RAM if
562
+ the weight of the CPU state dict + the biggest shard does not fit. Will default to `True` if the device map
563
+ picked contains `"disk"` values.
564
+ skip_keys (`str` or `List[str]`, *optional*):
565
+ A list of keys to ignore when moving inputs or outputs between devices.
566
+ preload_module_classes (`List[str]`, *optional*):
567
+ A list of classes whose instances should load all their weights (even in the submodules) at the beginning
568
+ of the forward. This should only be used for classes that have submodules which are registered but not
569
+ called directly during the forward, for instance if a `dense` linear layer is registered, but at forward,
570
+ `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly.
571
+ force_hooks (`bool`, *optional*, defaults to `False`):
572
+ Whether or not to force device hooks to be attached to the model even if all layers are dispatched to a
573
+ single device.
574
+ strict (`bool`, *optional*, defaults to `False`):
575
+ Whether to strictly enforce that the keys in the checkpoint state_dict match the keys of the model's
576
+ state_dict.
577
+ full_state_dict (`bool`, *optional*, defaults to `True`): if this is set to `True`, all the tensors in the
578
+ loaded state_dict will be gathered. No ShardedTensor and DTensor will be in the loaded state_dict.
579
+ broadcast_from_rank0 (`False`, *optional*, defaults to `False`): when the option is `True`, a distributed
580
+ `ProcessGroup` must be initialized. rank0 should receive a full state_dict and will broadcast the tensors
581
+ in the state_dict one by one to other ranks. Other ranks will receive the tensors and shard (if applicable)
582
+ according to the local shards in the model.
583
+
584
+ Example:
585
+
586
+ ```python
587
+ >>> from accelerate import init_empty_weights, load_checkpoint_and_dispatch
588
+ >>> from huggingface_hub import hf_hub_download
589
+ >>> from transformers import AutoConfig, AutoModelForCausalLM
590
+
591
+ >>> # Download the Weights
592
+ >>> checkpoint = "EleutherAI/gpt-j-6B"
593
+ >>> weights_location = hf_hub_download(checkpoint, "pytorch_model.bin")
594
+
595
+ >>> # Create a model and initialize it with empty weights
596
+ >>> config = AutoConfig.from_pretrained(checkpoint)
597
+ >>> with init_empty_weights():
598
+ ... model = AutoModelForCausalLM.from_config(config)
599
+
600
+ >>> # Load the checkpoint and dispatch it to the right devices
601
+ >>> model = load_checkpoint_and_dispatch(
602
+ ... model, weights_location, device_map="auto", no_split_module_classes=["GPTJBlock"]
603
+ ... )
604
+ ```
605
+ """
606
+ if isinstance(device_map, str) and device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]:
607
+ raise ValueError(
608
+ "If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or 'sequential'."
609
+ )
610
+ if isinstance(device_map, str):
611
+ if device_map != "sequential":
612
+ max_memory = get_balanced_memory(
613
+ model,
614
+ max_memory=max_memory,
615
+ no_split_module_classes=no_split_module_classes,
616
+ dtype=dtype,
617
+ low_zero=(device_map == "balanced_low_0"),
618
+ )
619
+ device_map = infer_auto_device_map(
620
+ model,
621
+ max_memory=max_memory,
622
+ no_split_module_classes=no_split_module_classes,
623
+ dtype=dtype,
624
+ offload_buffers=offload_buffers,
625
+ )
626
+ if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
627
+ offload_state_dict = True
628
+ load_checkpoint_in_model(
629
+ model,
630
+ checkpoint,
631
+ device_map=device_map,
632
+ offload_folder=offload_folder,
633
+ dtype=dtype,
634
+ offload_state_dict=offload_state_dict,
635
+ offload_buffers=offload_buffers,
636
+ strict=strict,
637
+ full_state_dict=full_state_dict,
638
+ broadcast_from_rank0=broadcast_from_rank0,
639
+ )
640
+ if device_map is None:
641
+ return model
642
+ return dispatch_model(
643
+ model,
644
+ device_map=device_map,
645
+ offload_dir=offload_folder,
646
+ offload_buffers=offload_buffers,
647
+ skip_keys=skip_keys,
648
+ preload_module_classes=preload_module_classes,
649
+ force_hooks=force_hooks,
650
+ )
651
+
652
+
653
+ def attach_layerwise_casting_hooks(
654
+ module: torch.nn.Module,
655
+ storage_dtype: torch.dtype,
656
+ compute_dtype: torch.dtype,
657
+ skip_modules_pattern: Union[str, tuple[str, ...]] = None,
658
+ skip_modules_classes: Optional[tuple[type[torch.nn.Module], ...]] = None,
659
+ non_blocking: bool = False,
660
+ ) -> None:
661
+ r"""
662
+ Applies layerwise casting to a given module. The module expected here is a PyTorch `nn.Module`. This is helpful for
663
+ reducing memory requirements when one doesn't want to fully quantize a model. Model params can be kept in say,
664
+ `torch.float8_e4m3fn` and upcasted to a higher precision like `torch.bfloat16` during forward pass and downcasted
665
+ back to `torch.float8_e4m3fn` to realize memory savings.
666
+
667
+ Args:
668
+ module (`torch.nn.Module`):
669
+ The module whose leaf modules will be cast to a high precision dtype for computation, and to a low
670
+ precision dtype for storage.
671
+ storage_dtype (`torch.dtype`):
672
+ The dtype to cast the module to before/after the forward pass for storage.
673
+ compute_dtype (`torch.dtype`):
674
+ The dtype to cast the module to during the forward pass for computation.
675
+ skip_modules_pattern (`tuple[str, ...]`, defaults to `None`):
676
+ A list of patterns to match the names of the modules to skip during the layerwise casting process. If set
677
+ to `None` alongside `skip_modules_classes` being `None`, the layerwise casting is applied directly to the
678
+ module instead of its internal submodules.
679
+ skip_modules_classes (`tuple[type[torch.nn.Module], ...]`, defaults to `None`):
680
+ A list of module classes to skip during the layerwise casting process.
681
+ non_blocking (`bool`, defaults to `False`):
682
+ If `True`, the weight casting operations are non-blocking.
683
+
684
+ Example:
685
+
686
+ ```python
687
+ >>> from accelerate.hooks import attach_layerwise_casting_hooks
688
+ >>> from transformers import AutoModelForCausalLM
689
+ >>> import torch
690
+
691
+ >>> # Model
692
+ >>> checkpoint = "EleutherAI/gpt-j-6B"
693
+ >>> model = AutoModelForCausalLM.from_pretrained(checkpoint)
694
+
695
+ >>> # Attach hooks and perform inference
696
+ >>> attach_layerwise_casting_hooks(model, storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16)
697
+ >>> with torch.no_grad():
698
+ ... model(...)
699
+ ```
700
+
701
+ Users can also pass modules they want to avoid from getting downcasted.
702
+
703
+ ```py
704
+ >>> attach_layerwise_casting_hooks(
705
+ ... model, storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16, skip_modules_pattern=["norm"]
706
+ ... )
707
+ ```
708
+ """
709
+ _attach_layerwise_casting_hooks(
710
+ module, storage_dtype, compute_dtype, skip_modules_pattern, skip_modules_classes, non_blocking
711
+ )
712
+
713
+
714
+ def _attach_layerwise_casting_hooks(
715
+ module: torch.nn.Module,
716
+ storage_dtype: torch.dtype,
717
+ compute_dtype: torch.dtype,
718
+ skip_modules_pattern: Union[str, tuple[str, ...]] = None,
719
+ skip_modules_classes: Optional[tuple[type[torch.nn.Module], ...]] = None,
720
+ non_blocking: bool = False,
721
+ _prefix: str = "",
722
+ ):
723
+ should_skip = (skip_modules_classes is not None and isinstance(module, skip_modules_classes)) or (
724
+ skip_modules_pattern is not None and any(re.search(pattern, _prefix) for pattern in skip_modules_pattern)
725
+ )
726
+ if should_skip:
727
+ logger.debug(f'Skipping layerwise casting for layer "{_prefix}"')
728
+ return
729
+
730
+ if isinstance(module, SUPPORTED_PYTORCH_LAYERS_FOR_UPCASTING):
731
+ logger.debug(f'Applying layerwise casting to layer "{_prefix}"')
732
+ add_hook_to_module(
733
+ module,
734
+ LayerwiseCastingHook(storage_dtype=storage_dtype, compute_dtype=compute_dtype, non_blocking=non_blocking),
735
+ append=True,
736
+ )
737
+ return
738
+
739
+ for name, submodule in module.named_children():
740
+ layer_name = f"{_prefix}.{name}" if _prefix else name
741
+ _attach_layerwise_casting_hooks(
742
+ submodule,
743
+ storage_dtype,
744
+ compute_dtype,
745
+ skip_modules_pattern,
746
+ skip_modules_classes,
747
+ non_blocking,
748
+ _prefix=layer_name,
749
+ )
750
+
751
+
752
+ def _attach_context_parallel_hooks(
753
+ model: nn.Module,
754
+ ):
755
+ """
756
+ Monkeypatch huggingface's `transformers` model to fix attention mask issues when using context parallelism.
757
+
758
+ This function attaches forward_pre_hooks to each self_attn module of the model, where each hook checks the
759
+ args/kwargs, if they contain an attention mask, if it does, it will remove this mask, check if it is a causal mask,
760
+ if yes, will add a kwarg `is_causal=True`, otherwise will raise an error. This is because context parallelism does
761
+ not support attention masks. This function modifies the model in place.
762
+
763
+ Args:
764
+ model (`nn.Module`):
765
+ The model to attach the hooks to.
766
+
767
+ """
768
+
769
+ def _self_attn_pre_forward_hook(_module, module_args, module_kwargs):
770
+ if "attention_mask" in module_kwargs:
771
+ module_kwargs["attention_mask"] = None
772
+ module_kwargs["is_causal"] = True
773
+
774
+ return module_args, module_kwargs
775
+
776
+ for name, module in model.named_modules():
777
+ # We hope (assume) that if user uses their own model (without this structure which transformers uses), they read the docs saying they can't pass in attention masks
778
+ # Then these cases can happen:
779
+ # 1) some modules end with a `self-attn` module, in which case we attach the hook, but the
780
+ # there's no attention mask kwarg -> hook is a no-op
781
+ # 2) some modules end with a `self-attn` module, in which case we attach the hook, and the
782
+ # attention mask kwarg is passed -> hook will remove the attention mask and add
783
+ # `is_causal=True` kwarg, which either crashes the training or fixes it
784
+ # (training would crash anyway as attention mask isn't supported)
785
+ # 3) no modules end with a `self-attn` module, in which case we don't attach the hook, this is
786
+ # a no-op as well
787
+ if name.endswith("self_attn"):
788
+ # we want the hook to be executed first, to avoid any other hooks doing work on the attention mask
789
+ module.register_forward_pre_hook(_self_attn_pre_forward_hook, with_kwargs=True, prepend=True)
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/checkpointing.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import random
16
+ from pathlib import Path
17
+
18
+ import numpy as np
19
+ import torch
20
+ from safetensors.torch import load_model
21
+
22
+ from .utils import (
23
+ MODEL_NAME,
24
+ OPTIMIZER_NAME,
25
+ RNG_STATE_NAME,
26
+ SAFE_MODEL_NAME,
27
+ SAFE_WEIGHTS_NAME,
28
+ SAMPLER_NAME,
29
+ SCALER_NAME,
30
+ SCHEDULER_NAME,
31
+ WEIGHTS_NAME,
32
+ get_pretty_name,
33
+ is_cuda_available,
34
+ is_hpu_available,
35
+ is_mlu_available,
36
+ is_musa_available,
37
+ is_sdaa_available,
38
+ is_torch_version,
39
+ is_torch_xla_available,
40
+ is_xpu_available,
41
+ load,
42
+ save,
43
+ )
44
+
45
+
46
+ if is_torch_version(">=", "2.4.0"):
47
+ from torch.amp import GradScaler
48
+ else:
49
+ from torch.cuda.amp import GradScaler
50
+
51
+ if is_torch_xla_available():
52
+ import torch_xla.core.xla_model as xm
53
+
54
+ from .logging import get_logger
55
+ from .state import PartialState
56
+
57
+
58
+ logger = get_logger(__name__)
59
+
60
+
61
+ def save_accelerator_state(
62
+ output_dir: str,
63
+ model_states: list[dict],
64
+ optimizers: list,
65
+ schedulers: list,
66
+ dataloaders: list,
67
+ process_index: int,
68
+ step: int,
69
+ scaler: GradScaler = None,
70
+ save_on_each_node: bool = False,
71
+ safe_serialization: bool = True,
72
+ ):
73
+ """
74
+ Saves the current states of the models, optimizers, scaler, and RNG generators to a given directory.
75
+
76
+ <Tip>
77
+
78
+ If `safe_serialization` is `True`, models will be saved with `safetensors` while the rest are saved using native
79
+ `pickle`.
80
+
81
+ </Tip>
82
+
83
+ Args:
84
+ output_dir (`str` or `os.PathLike`):
85
+ The name of the folder to save all relevant weights and states.
86
+ model_states (`List[torch.nn.Module]`):
87
+ A list of model states
88
+ optimizers (`List[torch.optim.Optimizer]`):
89
+ A list of optimizer instances
90
+ schedulers (`List[torch.optim.lr_scheduler._LRScheduler]`):
91
+ A list of learning rate schedulers
92
+ dataloaders (`List[torch.utils.data.DataLoader]`):
93
+ A list of dataloader instances to save their sampler states
94
+ process_index (`int`):
95
+ The current process index in the Accelerator state
96
+ step (`int`):
97
+ The current step in the internal step tracker
98
+ scaler (`torch.amp.GradScaler`, *optional*):
99
+ An optional gradient scaler instance to save;
100
+ save_on_each_node (`bool`, *optional*):
101
+ Whether to save on every node, or only the main node.
102
+ safe_serialization (`bool`, *optional*, defaults to `True`):
103
+ Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).
104
+ """
105
+ output_dir = Path(output_dir)
106
+ # Model states
107
+ for i, state in enumerate(model_states):
108
+ weights_name = WEIGHTS_NAME if not safe_serialization else SAFE_WEIGHTS_NAME
109
+ if i > 0:
110
+ weights_name = weights_name.replace(".", f"_{i}.")
111
+ output_model_file = output_dir.joinpath(weights_name)
112
+ save(state, output_model_file, save_on_each_node=save_on_each_node, safe_serialization=safe_serialization)
113
+ logger.info(f"Model weights saved in {output_model_file}")
114
+ # Optimizer states
115
+ for i, opt in enumerate(optimizers):
116
+ state = opt.state_dict()
117
+ optimizer_name = f"{OPTIMIZER_NAME}.bin" if i == 0 else f"{OPTIMIZER_NAME}_{i}.bin"
118
+ output_optimizer_file = output_dir.joinpath(optimizer_name)
119
+ save(state, output_optimizer_file, save_on_each_node=save_on_each_node, safe_serialization=False)
120
+ logger.info(f"Optimizer state saved in {output_optimizer_file}")
121
+ # Scheduler states
122
+ for i, scheduler in enumerate(schedulers):
123
+ state = scheduler.state_dict()
124
+ scheduler_name = f"{SCHEDULER_NAME}.bin" if i == 0 else f"{SCHEDULER_NAME}_{i}.bin"
125
+ output_scheduler_file = output_dir.joinpath(scheduler_name)
126
+ save(state, output_scheduler_file, save_on_each_node=save_on_each_node, safe_serialization=False)
127
+ logger.info(f"Scheduler state saved in {output_scheduler_file}")
128
+ # DataLoader states
129
+ for i, dataloader in enumerate(dataloaders):
130
+ sampler_name = f"{SAMPLER_NAME}.bin" if i == 0 else f"{SAMPLER_NAME}_{i}.bin"
131
+ output_sampler_file = output_dir.joinpath(sampler_name)
132
+ # Only save if we have our custom sampler
133
+ from .data_loader import IterableDatasetShard, SeedableRandomSampler
134
+
135
+ if isinstance(dataloader.dataset, IterableDatasetShard):
136
+ sampler = dataloader.get_sampler()
137
+ if isinstance(sampler, SeedableRandomSampler):
138
+ save(sampler, output_sampler_file, save_on_each_node=save_on_each_node, safe_serialization=False)
139
+ if getattr(dataloader, "use_stateful_dataloader", False):
140
+ dataloader_state_dict_name = "dl_state_dict.bin" if i == 0 else f"dl_state_dict_{i}.bin"
141
+ output_dataloader_state_dict_file = output_dir.joinpath(dataloader_state_dict_name)
142
+ state_dict = dataloader.state_dict()
143
+ torch.save(state_dict, output_dataloader_state_dict_file)
144
+ logger.info(f"Sampler state for dataloader {i} saved in {output_sampler_file}")
145
+
146
+ # GradScaler state
147
+ if scaler is not None:
148
+ state = scaler.state_dict()
149
+ output_scaler_file = output_dir.joinpath(SCALER_NAME)
150
+ torch.save(state, output_scaler_file)
151
+ logger.info(f"Gradient scaler state saved in {output_scaler_file}")
152
+ # Random number generator states
153
+ states = {}
154
+ states_name = f"{RNG_STATE_NAME}_{process_index}.pkl"
155
+ states["step"] = step
156
+ states["random_state"] = random.getstate()
157
+ states["numpy_random_seed"] = np.random.get_state()
158
+ states["torch_manual_seed"] = torch.get_rng_state()
159
+ if is_xpu_available():
160
+ states["torch_xpu_manual_seed"] = torch.xpu.get_rng_state_all()
161
+ if is_mlu_available():
162
+ states["torch_mlu_manual_seed"] = torch.mlu.get_rng_state_all()
163
+ elif is_sdaa_available():
164
+ states["torch_sdaa_manual_seed"] = torch.sdaa.get_rng_state_all()
165
+ elif is_musa_available():
166
+ states["torch_musa_manual_seed"] = torch.musa.get_rng_state_all()
167
+ if is_hpu_available():
168
+ states["torch_hpu_manual_seed"] = torch.hpu.get_rng_state_all()
169
+ if is_cuda_available():
170
+ states["torch_cuda_manual_seed"] = torch.cuda.get_rng_state_all()
171
+ if is_torch_xla_available():
172
+ states["xm_seed"] = xm.get_rng_state()
173
+ output_states_file = output_dir.joinpath(states_name)
174
+ torch.save(states, output_states_file)
175
+ logger.info(f"Random states saved in {output_states_file}")
176
+ return output_dir
177
+
178
+
179
+ def load_accelerator_state(
180
+ input_dir,
181
+ models,
182
+ optimizers,
183
+ schedulers,
184
+ dataloaders,
185
+ process_index,
186
+ scaler=None,
187
+ map_location=None,
188
+ load_kwargs=None,
189
+ **load_model_func_kwargs,
190
+ ):
191
+ """
192
+ Loads states of the models, optimizers, scaler, and RNG generators from a given directory.
193
+
194
+ Args:
195
+ input_dir (`str` or `os.PathLike`):
196
+ The name of the folder to load all relevant weights and states.
197
+ models (`List[torch.nn.Module]`):
198
+ A list of model instances
199
+ optimizers (`List[torch.optim.Optimizer]`):
200
+ A list of optimizer instances
201
+ schedulers (`List[torch.optim.lr_scheduler._LRScheduler]`):
202
+ A list of learning rate schedulers
203
+ process_index (`int`):
204
+ The current process index in the Accelerator state
205
+ scaler (`torch.amp.GradScaler`, *optional*):
206
+ An optional *GradScaler* instance to load
207
+ map_location (`str`, *optional*):
208
+ What device to load the optimizer state onto. Should be one of either "cpu" or "on_device".
209
+ load_kwargs (`dict`, *optional*):
210
+ Additional arguments that can be passed to the `load` function.
211
+ load_model_func_kwargs (`dict`, *optional*):
212
+ Additional arguments that can be passed to the model's `load_state_dict` method.
213
+
214
+ Returns:
215
+ `dict`: Contains the `Accelerator` attributes to override while loading the state.
216
+ """
217
+ # stores the `Accelerator` attributes to override
218
+ override_attributes = dict()
219
+ if map_location not in [None, "cpu", "on_device"]:
220
+ raise TypeError(
221
+ "Unsupported optimizer map location passed, please choose one of `None`, `'cpu'`, or `'on_device'`"
222
+ )
223
+ if map_location is None:
224
+ map_location = "cpu"
225
+ elif map_location == "on_device":
226
+ map_location = PartialState().device
227
+
228
+ if load_kwargs is None:
229
+ load_kwargs = {}
230
+
231
+ input_dir = Path(input_dir)
232
+ # Model states
233
+ for i, model in enumerate(models):
234
+ ending = f"_{i}" if i > 0 else ""
235
+ input_model_file = input_dir.joinpath(f"{SAFE_MODEL_NAME}{ending}.safetensors")
236
+ if input_model_file.exists():
237
+ load_model(model, input_model_file, device=str(map_location), **load_model_func_kwargs)
238
+ else:
239
+ # Load with torch
240
+ input_model_file = input_dir.joinpath(f"{MODEL_NAME}{ending}.bin")
241
+ state_dict = load(input_model_file, map_location=map_location)
242
+ model.load_state_dict(state_dict, **load_model_func_kwargs)
243
+ logger.info("All model weights loaded successfully")
244
+
245
+ # Optimizer states
246
+ for i, opt in enumerate(optimizers):
247
+ optimizer_name = f"{OPTIMIZER_NAME}.bin" if i == 0 else f"{OPTIMIZER_NAME}_{i}.bin"
248
+ input_optimizer_file = input_dir.joinpath(optimizer_name)
249
+ optimizer_state = load(input_optimizer_file, map_location=map_location, **load_kwargs)
250
+ optimizers[i].load_state_dict(optimizer_state)
251
+ logger.info("All optimizer states loaded successfully")
252
+
253
+ # Scheduler states
254
+ for i, scheduler in enumerate(schedulers):
255
+ scheduler_name = f"{SCHEDULER_NAME}.bin" if i == 0 else f"{SCHEDULER_NAME}_{i}.bin"
256
+ input_scheduler_file = input_dir.joinpath(scheduler_name)
257
+ scheduler_state = load(input_scheduler_file, **load_kwargs)
258
+ scheduler.load_state_dict(scheduler_state)
259
+ logger.info("All scheduler states loaded successfully")
260
+
261
+ for i, dataloader in enumerate(dataloaders):
262
+ sampler_name = f"{SAMPLER_NAME}.bin" if i == 0 else f"{SAMPLER_NAME}_{i}.bin"
263
+ input_sampler_file = input_dir.joinpath(sampler_name)
264
+ # Only load if we have our custom sampler
265
+ from .data_loader import IterableDatasetShard, SeedableRandomSampler
266
+
267
+ if isinstance(dataloader.dataset, IterableDatasetShard):
268
+ sampler = dataloader.get_sampler()
269
+ if isinstance(sampler, SeedableRandomSampler):
270
+ sampler = dataloader.set_sampler(load(input_sampler_file))
271
+ if getattr(dataloader, "use_stateful_dataloader", False):
272
+ dataloader_state_dict_name = "dl_state_dict.bin" if i == 0 else f"dl_state_dict_{i}.bin"
273
+ input_dataloader_state_dict_file = input_dir.joinpath(dataloader_state_dict_name)
274
+ if input_dataloader_state_dict_file.exists():
275
+ state_dict = load(input_dataloader_state_dict_file, **load_kwargs)
276
+ dataloader.load_state_dict(state_dict)
277
+ logger.info("All dataloader sampler states loaded successfully")
278
+
279
+ # GradScaler state
280
+ if scaler is not None:
281
+ input_scaler_file = input_dir.joinpath(SCALER_NAME)
282
+ scaler_state = load(input_scaler_file)
283
+ scaler.load_state_dict(scaler_state)
284
+ logger.info("GradScaler state loaded successfully")
285
+
286
+ # Random states
287
+ try:
288
+ states = load(input_dir.joinpath(f"{RNG_STATE_NAME}_{process_index}.pkl"))
289
+ if "step" in states:
290
+ override_attributes["step"] = states["step"]
291
+ random.setstate(states["random_state"])
292
+ np.random.set_state(states["numpy_random_seed"])
293
+ torch.set_rng_state(states["torch_manual_seed"])
294
+ if is_xpu_available():
295
+ torch.xpu.set_rng_state_all(states["torch_xpu_manual_seed"])
296
+ if is_mlu_available():
297
+ torch.mlu.set_rng_state_all(states["torch_mlu_manual_seed"])
298
+ elif is_sdaa_available():
299
+ torch.sdaa.set_rng_state_all(states["torch_sdaa_manual_seed"])
300
+ elif is_musa_available():
301
+ torch.musa.set_rng_state_all(states["torch_musa_manual_seed"])
302
+ else:
303
+ torch.cuda.set_rng_state_all(states["torch_cuda_manual_seed"])
304
+ if is_torch_xla_available():
305
+ xm.set_rng_state(states["xm_seed"])
306
+ logger.info("All random states loaded successfully")
307
+ except Exception:
308
+ logger.info("Could not load random states")
309
+
310
+ return override_attributes
311
+
312
+
313
+ def save_custom_state(obj, path, index: int = 0, save_on_each_node: bool = False):
314
+ """
315
+ Saves the state of `obj` to `{path}/custom_checkpoint_{index}.pkl`
316
+ """
317
+ # Should this be the right way to get a qual_name type value from `obj`?
318
+ save_location = Path(path) / f"custom_checkpoint_{index}.pkl"
319
+ logger.info(f"Saving the state of {get_pretty_name(obj)} to {save_location}")
320
+ save(obj.state_dict(), save_location, save_on_each_node=save_on_each_node)
321
+
322
+
323
+ def load_custom_state(obj, path, index: int = 0):
324
+ """
325
+ Loads the state of `obj` at `{path}/custom_checkpoint_{index}.pkl`. Will always set `weights_only=False` when
326
+ loading the state.
327
+ """
328
+ load_location = f"{path}/custom_checkpoint_{index}.pkl"
329
+ logger.info(f"Loading the state of {get_pretty_name(obj)} from {load_location}")
330
+ obj.load_state_dict(load(load_location, map_location="cpu", weights_only=False))
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/accelerate_cli.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2021 The HuggingFace Team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ from accelerate.commands.config import get_config_parser
18
+ from accelerate.commands.env import env_command_parser
19
+ from accelerate.commands.estimate import estimate_command_parser
20
+ from accelerate.commands.launch import launch_command_parser
21
+ from accelerate.commands.merge import merge_command_parser
22
+ from accelerate.commands.test import test_command_parser
23
+ from accelerate.commands.to_fsdp2 import to_fsdp2_command_parser
24
+ from accelerate.commands.tpu import tpu_command_parser
25
+ from accelerate.commands.utils import CustomArgumentParser
26
+
27
+
28
+ def main():
29
+ parser = CustomArgumentParser("Accelerate CLI tool", usage="accelerate <command> [<args>]", allow_abbrev=False)
30
+ subparsers = parser.add_subparsers(help="accelerate command helpers")
31
+
32
+ # Register commands
33
+ get_config_parser(subparsers=subparsers)
34
+ estimate_command_parser(subparsers=subparsers)
35
+ env_command_parser(subparsers=subparsers)
36
+ launch_command_parser(subparsers=subparsers)
37
+ merge_command_parser(subparsers=subparsers)
38
+ tpu_command_parser(subparsers=subparsers)
39
+ test_command_parser(subparsers=subparsers)
40
+ to_fsdp2_command_parser(subparsers=subparsers)
41
+
42
+ # Let's go
43
+ args = parser.parse_args()
44
+
45
+ if not hasattr(args, "func"):
46
+ parser.print_help()
47
+ exit(1)
48
+
49
+ # Run
50
+ args.func(args)
51
+
52
+
53
+ if __name__ == "__main__":
54
+ main()
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/__init__.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2021 The HuggingFace Team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import argparse
18
+
19
+ from .config import config_command_parser
20
+ from .config_args import default_config_file, load_config_from_file # noqa: F401
21
+ from .default import default_command_parser
22
+ from .update import update_command_parser
23
+
24
+
25
+ def get_config_parser(subparsers=None):
26
+ parent_parser = argparse.ArgumentParser(add_help=False, allow_abbrev=False)
27
+ # The main config parser
28
+ config_parser = config_command_parser(subparsers)
29
+ # The subparser to add commands to
30
+ subcommands = config_parser.add_subparsers(title="subcommands", dest="subcommand")
31
+
32
+ # Then add other parsers with the parent parser
33
+ default_command_parser(subcommands, parents=[parent_parser])
34
+ update_command_parser(subcommands, parents=[parent_parser])
35
+
36
+ return config_parser
37
+
38
+
39
+ def main():
40
+ config_parser = get_config_parser()
41
+ args = config_parser.parse_args()
42
+
43
+ if not hasattr(args, "func"):
44
+ config_parser.print_help()
45
+ exit(1)
46
+
47
+ # Run
48
+ args.func(args)
49
+
50
+
51
+ if __name__ == "__main__":
52
+ main()
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/cluster.py ADDED
@@ -0,0 +1,917 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2021 The HuggingFace Team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import os
18
+
19
+ from ...utils import (
20
+ ComputeEnvironment,
21
+ DistributedType,
22
+ is_deepspeed_available,
23
+ is_fp8_available,
24
+ is_hpu_available,
25
+ is_mlu_available,
26
+ is_mps_available,
27
+ is_msamp_available,
28
+ is_musa_available,
29
+ is_npu_available,
30
+ is_sdaa_available,
31
+ is_transformer_engine_available,
32
+ is_transformers_available,
33
+ is_xpu_available,
34
+ )
35
+ from ...utils.constants import (
36
+ DEEPSPEED_MULTINODE_LAUNCHERS,
37
+ FSDP2_STATE_DICT_TYPE,
38
+ FSDP_AUTO_WRAP_POLICY,
39
+ FSDP_BACKWARD_PREFETCH,
40
+ FSDP_SHARDING_STRATEGY,
41
+ FSDP_STATE_DICT_TYPE,
42
+ TORCH_DYNAMO_MODES,
43
+ )
44
+ from .config_args import ClusterConfig
45
+ from .config_utils import (
46
+ DYNAMO_BACKENDS,
47
+ _ask_field,
48
+ _ask_options,
49
+ _convert_distributed_mode,
50
+ _convert_dynamo_backend,
51
+ _convert_fp8_backend,
52
+ _convert_mixed_precision,
53
+ _convert_yes_no_to_bool,
54
+ )
55
+
56
+
57
+ def get_cluster_input():
58
+ distributed_type = _ask_options(
59
+ "Which type of machine are you using?",
60
+ [
61
+ "No distributed training",
62
+ "multi-CPU",
63
+ "multi-XPU",
64
+ "multi-HPU",
65
+ "multi-GPU",
66
+ "multi-NPU",
67
+ "multi-MLU",
68
+ "multi-SDAA",
69
+ "multi-MUSA",
70
+ "TPU",
71
+ ],
72
+ _convert_distributed_mode,
73
+ )
74
+
75
+ machine_rank = 0
76
+ num_machines = 1
77
+ num_processes = 1
78
+ gpu_ids = None
79
+ main_process_ip = None
80
+ main_process_port = None
81
+ rdzv_backend = "static"
82
+ same_network = True
83
+ debug = False
84
+
85
+ if distributed_type in [
86
+ DistributedType.MULTI_GPU,
87
+ DistributedType.MULTI_MLU,
88
+ DistributedType.MULTI_SDAA,
89
+ DistributedType.MULTI_MUSA,
90
+ DistributedType.MULTI_NPU,
91
+ DistributedType.MULTI_XPU,
92
+ DistributedType.MULTI_CPU,
93
+ DistributedType.MULTI_HPU,
94
+ ]:
95
+ num_machines = _ask_field(
96
+ "How many different machines will you use (use more than 1 for multi-node training)? [1]: ",
97
+ int,
98
+ default=1,
99
+ )
100
+ if num_machines > 1:
101
+ machine_rank = _ask_options(
102
+ "What is the rank of this machine?",
103
+ list(range(num_machines)),
104
+ int,
105
+ )
106
+ main_process_ip = _ask_field(
107
+ "What is the IP address of the machine that will host the main process? ",
108
+ )
109
+ main_process_port = _ask_field(
110
+ "What is the port you will use to communicate with the main process? ",
111
+ int,
112
+ )
113
+ same_network = _ask_field(
114
+ "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]: ",
115
+ _convert_yes_no_to_bool,
116
+ default=True,
117
+ error_message="Please enter yes or no.",
118
+ )
119
+ if not same_network:
120
+ rdzv_backend = _ask_field(
121
+ "What rendezvous backend will you use? ('static', 'c10d', ...): ", default="static"
122
+ )
123
+ debug = _ask_field(
124
+ "Should distributed operations be checked while running for errors? This can avoid timeout issues but will be slower. [yes/NO]: ",
125
+ _convert_yes_no_to_bool,
126
+ default=False,
127
+ error_message="Please enter yes or no.",
128
+ )
129
+
130
+ if distributed_type == DistributedType.NO:
131
+ use_cpu = _ask_field(
132
+ "Do you want to run your training on CPU only (even if a GPU / Apple Silicon / Ascend NPU device is available)? [yes/NO]:",
133
+ _convert_yes_no_to_bool,
134
+ default=False,
135
+ error_message="Please enter yes or no.",
136
+ )
137
+ elif distributed_type == DistributedType.MULTI_CPU:
138
+ use_cpu = True
139
+ else:
140
+ use_cpu = False
141
+
142
+ ipex_config = {}
143
+ mpirun_config = {}
144
+ if use_cpu or is_xpu_available():
145
+ ipex_config["ipex"] = _ask_field(
146
+ "Do you want to use Intel PyTorch Extension (IPEX) to speed up training on CPU/XPU? [yes/NO]:",
147
+ _convert_yes_no_to_bool,
148
+ default=False,
149
+ error_message="Please enter yes or no.",
150
+ )
151
+
152
+ if use_cpu:
153
+ if distributed_type == DistributedType.MULTI_CPU:
154
+ use_mpirun = _ask_field(
155
+ "Do you want accelerate to launch mpirun? [yes/NO]: ",
156
+ _convert_yes_no_to_bool,
157
+ default=False,
158
+ error_message="Please enter yes or no.",
159
+ )
160
+ if use_mpirun:
161
+ mpirun_hostfile = _ask_field(
162
+ "Please enter the path to the hostfile to use with mpirun [~/hostfile]: ",
163
+ str,
164
+ default="~/hostfile",
165
+ )
166
+ mpirun_config["mpirun_hostfile"] = os.path.expanduser(mpirun_hostfile.strip())
167
+ mpirun_config["mpirun_ccl"] = _ask_field("Enter the number of oneCCL worker threads [1]: ", default=1)
168
+
169
+ dynamo_config = {}
170
+ use_dynamo = _ask_field(
171
+ "Do you wish to optimize your script with torch dynamo?[yes/NO]:",
172
+ _convert_yes_no_to_bool,
173
+ default=False,
174
+ error_message="Please enter yes or no.",
175
+ )
176
+ if use_dynamo:
177
+ prefix = "dynamo_"
178
+ dynamo_config[prefix + "backend"] = _ask_options(
179
+ "Which dynamo backend would you like to use?",
180
+ [x.lower() for x in DYNAMO_BACKENDS],
181
+ _convert_dynamo_backend,
182
+ default=2,
183
+ )
184
+ use_custom_options = _ask_field(
185
+ "Do you want to customize the defaults sent to torch.compile? [yes/NO]: ",
186
+ _convert_yes_no_to_bool,
187
+ default=False,
188
+ error_message="Please enter yes or no.",
189
+ )
190
+
191
+ if use_custom_options:
192
+ dynamo_config[prefix + "mode"] = _ask_options(
193
+ "Which mode do you want to use?",
194
+ TORCH_DYNAMO_MODES,
195
+ lambda x: TORCH_DYNAMO_MODES[int(x)],
196
+ default=0,
197
+ )
198
+ dynamo_config[prefix + "use_fullgraph"] = _ask_field(
199
+ "Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: ",
200
+ _convert_yes_no_to_bool,
201
+ default=False,
202
+ error_message="Please enter yes or no.",
203
+ )
204
+ dynamo_config[prefix + "use_dynamic"] = _ask_field(
205
+ "Do you want to enable dynamic shape tracing? [yes/NO]: ",
206
+ _convert_yes_no_to_bool,
207
+ default=False,
208
+ error_message="Please enter yes or no.",
209
+ )
210
+ dynamo_config[prefix + "use_regional_compilation"] = _ask_field(
211
+ "Do you want to enable regional compilation? [yes/NO]: ",
212
+ _convert_yes_no_to_bool,
213
+ default=False,
214
+ error_message="Please enter yes or no.",
215
+ )
216
+
217
+ use_mps = not use_cpu and is_mps_available()
218
+ deepspeed_config = {}
219
+ if (
220
+ distributed_type
221
+ in [
222
+ DistributedType.MULTI_GPU,
223
+ DistributedType.MULTI_XPU,
224
+ DistributedType.MULTI_HPU,
225
+ DistributedType.MULTI_NPU,
226
+ DistributedType.MULTI_MLU,
227
+ DistributedType.MULTI_SDAA,
228
+ DistributedType.MULTI_MUSA,
229
+ DistributedType.NO,
230
+ ]
231
+ and not use_mps
232
+ ):
233
+ use_deepspeed = _ask_field(
234
+ "Do you want to use DeepSpeed? [yes/NO]: ",
235
+ _convert_yes_no_to_bool,
236
+ default=False,
237
+ error_message="Please enter yes or no.",
238
+ )
239
+ if use_deepspeed:
240
+ distributed_type = DistributedType.DEEPSPEED
241
+ assert is_deepspeed_available(), (
242
+ "DeepSpeed is not installed => run `pip3 install deepspeed` or build it from source"
243
+ )
244
+
245
+ if distributed_type == DistributedType.DEEPSPEED:
246
+ use_deepspeed_config = _ask_field(
247
+ "Do you want to specify a json file to a DeepSpeed config? [yes/NO]: ",
248
+ _convert_yes_no_to_bool,
249
+ default=False,
250
+ error_message="Please enter yes or no.",
251
+ )
252
+ if use_deepspeed_config:
253
+ deepspeed_config["deepspeed_config_file"] = _ask_field(
254
+ "Please enter the path to the json DeepSpeed config file: ",
255
+ str,
256
+ default="none",
257
+ )
258
+ else:
259
+ deepspeed_config["zero_stage"] = _ask_options(
260
+ "What should be your DeepSpeed's ZeRO optimization stage?",
261
+ [0, 1, 2, 3],
262
+ int,
263
+ default=2,
264
+ )
265
+
266
+ deepspeed_devices = ["none", "cpu", "nvme"]
267
+ if deepspeed_config["zero_stage"] >= 2:
268
+ deepspeed_config["offload_optimizer_device"] = _ask_options(
269
+ "Where to offload optimizer states?", deepspeed_devices, lambda x: deepspeed_devices[int(x)]
270
+ )
271
+ deepspeed_config["offload_param_device"] = _ask_options(
272
+ "Where to offload parameters?", deepspeed_devices, lambda x: deepspeed_devices[int(x)]
273
+ )
274
+ if deepspeed_config["offload_param_device"] == "nvme":
275
+ deepspeed_config["offload_param_nvme_path"] = _ask_field(
276
+ "Nvme Path to offload parameters?",
277
+ str,
278
+ default="/nvme",
279
+ )
280
+ if deepspeed_config["offload_optimizer_device"] == "nvme":
281
+ deepspeed_config["offload_optimizer_nvme_path"] = _ask_field(
282
+ "Nvme Path to offload optimizer states?",
283
+ str,
284
+ default="/nvme",
285
+ )
286
+ deepspeed_config["gradient_accumulation_steps"] = _ask_field(
287
+ "How many gradient accumulation steps you're passing in your script? [1]: ",
288
+ int,
289
+ default=1,
290
+ )
291
+ use_gradient_clipping = _ask_field(
292
+ "Do you want to use gradient clipping? [yes/NO]: ",
293
+ _convert_yes_no_to_bool,
294
+ default=False,
295
+ error_message="Please enter yes or no.",
296
+ )
297
+ if use_gradient_clipping:
298
+ deepspeed_config["gradient_clipping"] = _ask_field(
299
+ "What is the gradient clipping value? [1.0]: ",
300
+ float,
301
+ default=1.0,
302
+ )
303
+ if deepspeed_config["zero_stage"] == 3:
304
+ deepspeed_config["zero3_save_16bit_model"] = _ask_field(
305
+ "Do you want to save 16-bit model weights when using ZeRO Stage-3? [yes/NO]: ",
306
+ _convert_yes_no_to_bool,
307
+ default=False,
308
+ error_message="Please enter yes or no.",
309
+ )
310
+ deepspeed_config["zero3_init_flag"] = _ask_field(
311
+ "Do you want to enable `deepspeed.zero.Init` when using ZeRO Stage-3 for constructing massive models? [yes/NO]: ",
312
+ _convert_yes_no_to_bool,
313
+ default=False,
314
+ error_message="Please enter yes or no.",
315
+ )
316
+ if deepspeed_config["zero3_init_flag"]:
317
+ if not is_transformers_available():
318
+ raise Exception(
319
+ "When `zero3_init_flag` is set, it requires Transformers to be installed. "
320
+ "Please run `pip3 install transformers`."
321
+ )
322
+ use_moe = _ask_field(
323
+ "Do you want to enable Mixture-of-Experts training (MoE)? [yes/NO]: ",
324
+ _convert_yes_no_to_bool,
325
+ default=False,
326
+ error_message="Please enter yes or no.",
327
+ )
328
+ if use_moe:
329
+ deepspeed_config["deepspeed_moe_layer_cls_names"] = _ask_field(
330
+ "Specify the comma-separated list of transformers MoE layer class names (case-sensitive), e.g : "
331
+ " `MixtralSparseMoeBlock`, `Qwen2MoeSparseMoeBlock`, `JetMoEAttention,JetMoEBlock` ... : ",
332
+ str,
333
+ )
334
+
335
+ if num_machines > 1:
336
+ launcher_query = "Which Type of launcher do you want to use?"
337
+ deepspeed_config["deepspeed_multinode_launcher"] = _ask_options(
338
+ launcher_query,
339
+ DEEPSPEED_MULTINODE_LAUNCHERS,
340
+ lambda x: DEEPSPEED_MULTINODE_LAUNCHERS[int(x)],
341
+ )
342
+
343
+ if deepspeed_config["deepspeed_multinode_launcher"] != DEEPSPEED_MULTINODE_LAUNCHERS[1]:
344
+ deepspeed_config["deepspeed_hostfile"] = _ask_field(
345
+ "DeepSpeed configures multi-node compute resources with hostfile. "
346
+ "Each row is of the format `hostname slots=[num_gpus]`, e.g., `localhost slots=2`; "
347
+ "for more information please refer official [documentation]"
348
+ "(https://www.deepspeed.ai/getting-started/#resource-configuration-multi-node). "
349
+ "Please specify the location of hostfile: ",
350
+ str,
351
+ )
352
+
353
+ is_exclusion_filter = _ask_field(
354
+ "Do you want to specify exclusion filter string? [yes/NO]: ",
355
+ _convert_yes_no_to_bool,
356
+ default=False,
357
+ error_message="Please enter yes or no.",
358
+ )
359
+ if is_exclusion_filter:
360
+ deepspeed_config["deepspeed_exclusion_filter"] = _ask_field(
361
+ "DeepSpeed exclusion filter string: ",
362
+ str,
363
+ )
364
+
365
+ is_inclusion_filter = _ask_field(
366
+ "Do you want to specify inclusion filter string? [yes/NO]: ",
367
+ _convert_yes_no_to_bool,
368
+ default=False,
369
+ error_message="Please enter yes or no.",
370
+ )
371
+ if is_inclusion_filter:
372
+ deepspeed_config["deepspeed_inclusion_filter"] = _ask_field(
373
+ "DeepSpeed inclusion filter string: ",
374
+ str,
375
+ )
376
+
377
+ fsdp_config = {}
378
+
379
+ if distributed_type in [
380
+ DistributedType.MULTI_GPU,
381
+ DistributedType.MULTI_NPU,
382
+ DistributedType.MULTI_MLU,
383
+ DistributedType.MULTI_SDAA,
384
+ DistributedType.MULTI_MUSA,
385
+ DistributedType.MULTI_XPU,
386
+ DistributedType.MULTI_HPU,
387
+ ]:
388
+ use_fsdp = _ask_field(
389
+ "Do you want to use FullyShardedDataParallel? [yes/NO]: ",
390
+ _convert_yes_no_to_bool,
391
+ default=False,
392
+ error_message="Please enter yes or no.",
393
+ )
394
+ if use_fsdp:
395
+ distributed_type = DistributedType.FSDP
396
+ if distributed_type == DistributedType.FSDP:
397
+ fsdp_config["fsdp_version"] = _ask_options(
398
+ "What should be your FSDP version? [2]: ",
399
+ [1, 2],
400
+ lambda x: int(x) + 1,
401
+ default=1,
402
+ )
403
+ fsdp_version = fsdp_config["fsdp_version"] # extract to a variable to simplify usage later
404
+
405
+ if fsdp_version == 1:
406
+ sharding_strategy_query = "What should be your sharding strategy?"
407
+ fsdp_config["fsdp_reshard_after_forward"] = _ask_options(
408
+ sharding_strategy_query,
409
+ FSDP_SHARDING_STRATEGY,
410
+ lambda x: FSDP_SHARDING_STRATEGY[int(x)],
411
+ )
412
+ else:
413
+ fsdp_config["fsdp_reshard_after_forward"] = _ask_field(
414
+ "Do you want to enable resharding after forward? [YES/no]: ",
415
+ _convert_yes_no_to_bool,
416
+ default=True,
417
+ error_message="Please enter yes or no.",
418
+ )
419
+
420
+ fsdp_config["fsdp_offload_params"] = _ask_field(
421
+ "Do you want to offload parameters and gradients to CPU? [yes/NO]: ",
422
+ _convert_yes_no_to_bool,
423
+ default=False,
424
+ error_message="Please enter yes or no.",
425
+ )
426
+
427
+ fsdp_wrap_query = "What should be your auto wrap policy?"
428
+ fsdp_config["fsdp_auto_wrap_policy"] = _ask_options(
429
+ fsdp_wrap_query,
430
+ FSDP_AUTO_WRAP_POLICY,
431
+ lambda x: FSDP_AUTO_WRAP_POLICY[int(x)],
432
+ )
433
+ if fsdp_config["fsdp_auto_wrap_policy"] == FSDP_AUTO_WRAP_POLICY[0]:
434
+ use_no_split_modules = _ask_field(
435
+ "Do you want to use the model's `_no_split_modules` to wrap. Only applicable for 🤗 Transformers [yes/NO]: ",
436
+ _convert_yes_no_to_bool,
437
+ default=False,
438
+ error_message="Please enter yes or no.",
439
+ )
440
+ if not use_no_split_modules:
441
+ fsdp_config["fsdp_transformer_layer_cls_to_wrap"] = _ask_field(
442
+ "Specify the comma-separated list of transformer layer class names (case-sensitive) to wrap ,e.g, :"
443
+ "`BertLayer`, `GPTJBlock`, `T5Block`, `BertLayer,BertEmbeddings,BertSelfOutput` ...? : ",
444
+ str,
445
+ )
446
+ elif fsdp_config["fsdp_auto_wrap_policy"] == FSDP_AUTO_WRAP_POLICY[1]:
447
+ fsdp_config["fsdp_min_num_params"] = _ask_field(
448
+ "What should be your FSDP's minimum number of parameters for Default Auto Wrapping Policy? [1e8]: ",
449
+ int,
450
+ default=100000000,
451
+ )
452
+ # Removed in FSDP2, ask for user input for FSDP1
453
+ if fsdp_version == 1:
454
+ fsdp_backward_prefetch_query = "What should be your FSDP's backward prefetch policy?"
455
+ fsdp_config["fsdp_backward_prefetch"] = _ask_options(
456
+ fsdp_backward_prefetch_query,
457
+ FSDP_BACKWARD_PREFETCH,
458
+ lambda x: FSDP_BACKWARD_PREFETCH[int(x)],
459
+ )
460
+
461
+ fsdp_state_dict_type_query = "What should be your FSDP's state dict type?"
462
+ fsdp_config["fsdp_state_dict_type"] = _ask_options(
463
+ fsdp_state_dict_type_query,
464
+ FSDP_STATE_DICT_TYPE if fsdp_version == 1 else FSDP2_STATE_DICT_TYPE,
465
+ lambda x: FSDP_STATE_DICT_TYPE[int(x)] if fsdp_version == 1 else FSDP2_STATE_DICT_TYPE[int(x)],
466
+ default=0,
467
+ )
468
+ # Not implemented in FSDP2, ask for user input for FSDP1
469
+ if fsdp_version == 1:
470
+ fsdp_config["fsdp_forward_prefetch"] = _ask_field(
471
+ "Do you want to enable FSDP's forward prefetch policy? [yes/NO]: ",
472
+ _convert_yes_no_to_bool,
473
+ default=False,
474
+ error_message="Please enter yes or no.",
475
+ )
476
+ # Obsolete in FSDP2, ask for user input for FSDP1
477
+ if fsdp_version == 1:
478
+ fsdp_config["fsdp_use_orig_params"] = _ask_field(
479
+ "Do you want to enable FSDP's `use_orig_params` feature? [YES/no]: ",
480
+ _convert_yes_no_to_bool,
481
+ default=True,
482
+ error_message="Please enter yes or no.",
483
+ )
484
+ fsdp_config["fsdp_cpu_ram_efficient_loading"] = _ask_field(
485
+ "Do you want to enable CPU RAM efficient model loading? Only applicable for 🤗 Transformers models. [YES/no]: ",
486
+ _convert_yes_no_to_bool,
487
+ default=True,
488
+ error_message="Please enter yes or no.",
489
+ )
490
+ # Obsolete in FSDP2, ask for user input for FSDP1
491
+ if fsdp_version == 1:
492
+ if fsdp_config["fsdp_cpu_ram_efficient_loading"]:
493
+ fsdp_config["fsdp_sync_module_states"] = True
494
+ else:
495
+ fsdp_config["fsdp_sync_module_states"] = _ask_field(
496
+ "Do you want each individually wrapped FSDP unit to broadcast module parameters from rank 0 at the start? [YES/no]: ",
497
+ _convert_yes_no_to_bool,
498
+ default=True,
499
+ error_message="Please enter yes or no.",
500
+ )
501
+ fsdp_config["fsdp_activation_checkpointing"] = _ask_field(
502
+ "Do you want to enable FSDP activation checkpointing? [yes/NO]: ",
503
+ _convert_yes_no_to_bool,
504
+ default=False,
505
+ error_message="Please enter yes or no.",
506
+ )
507
+
508
+ parallelism_config = {}
509
+
510
+ if fsdp_config.get("fsdp_version", 1) == 2:
511
+ use_parallelism_config = _ask_field(
512
+ "Do you want to use the parallelism config? [yes/NO]: ",
513
+ _convert_yes_no_to_bool,
514
+ default=False,
515
+ error_message="Please enter yes or no.",
516
+ )
517
+
518
+ if use_parallelism_config:
519
+ prefix = "parallelism_config_"
520
+ parallelism_config[prefix + "dp_replicate_size"] = _ask_field(
521
+ "What is the data parallelism replicate size? [1]: ",
522
+ int,
523
+ default=1,
524
+ error_message="Please enter an integer.",
525
+ )
526
+
527
+ parallelism_config[prefix + "dp_shard_size"] = _ask_field(
528
+ "What is the FSDP shard size? [1]: ",
529
+ int,
530
+ default=1,
531
+ error_message="Please enter an integer.",
532
+ )
533
+
534
+ parallelism_config[prefix + "tp_size"] = _ask_field(
535
+ "What is the tensor parallelism size? [1]: ",
536
+ int,
537
+ default=1,
538
+ error_message="Please enter an integer.",
539
+ )
540
+
541
+ parallelism_config[prefix + "cp_size"] = _ask_field(
542
+ "What is the context parallelism size? [1]: ",
543
+ int,
544
+ default=1,
545
+ error_message="Please enter an integer.",
546
+ )
547
+ if parallelism_config[prefix + "cp_size"] > 1:
548
+ parallelism_config[prefix + "cp_comm_strategy"] = _ask_options(
549
+ "What is the compute parallelism communication strategy?",
550
+ ["allgather", "alltoall"],
551
+ lambda x: ["allgather", "alltoall"][int(x)],
552
+ default=0,
553
+ )
554
+
555
+ megatron_lm_config = {}
556
+ if distributed_type in [DistributedType.MULTI_GPU]:
557
+ use_megatron_lm = _ask_field(
558
+ "Do you want to use Megatron-LM ? [yes/NO]: ",
559
+ _convert_yes_no_to_bool,
560
+ default=False,
561
+ error_message="Please enter yes or no.",
562
+ )
563
+ if use_megatron_lm:
564
+ distributed_type = DistributedType.MEGATRON_LM
565
+ if distributed_type == DistributedType.MEGATRON_LM:
566
+ prefix = "megatron_lm_"
567
+ megatron_lm_config[prefix + "tp_degree"] = _ask_field(
568
+ "What is the Tensor Parallelism degree/size? [1]:",
569
+ int,
570
+ default=1,
571
+ error_message="Please enter an integer.",
572
+ )
573
+ if megatron_lm_config[prefix + "tp_degree"] > 1:
574
+ megatron_lm_config[prefix + "sequence_parallelism"] = _ask_field(
575
+ "Do you want to enable Sequence Parallelism? [YES/no]: ",
576
+ _convert_yes_no_to_bool,
577
+ default=True,
578
+ error_message="Please enter yes or no.",
579
+ )
580
+
581
+ megatron_lm_config[prefix + "pp_degree"] = _ask_field(
582
+ "What is the Pipeline Parallelism degree/size? [1]:",
583
+ int,
584
+ default=1,
585
+ error_message="Please enter an integer.",
586
+ )
587
+ if megatron_lm_config[prefix + "pp_degree"] > 1:
588
+ megatron_lm_config[prefix + "num_micro_batches"] = _ask_field(
589
+ "What is the number of micro-batches? [1]:",
590
+ int,
591
+ default=1,
592
+ error_message="Please enter an integer.",
593
+ )
594
+
595
+ megatron_lm_config[prefix + "recompute_activations"] = _ask_field(
596
+ "Do you want to enable selective activation recomputation? [YES/no]: ",
597
+ _convert_yes_no_to_bool,
598
+ default=True,
599
+ error_message="Please enter yes or no.",
600
+ )
601
+
602
+ megatron_lm_config[prefix + "use_distributed_optimizer"] = _ask_field(
603
+ "Do you want to use distributed optimizer "
604
+ "which shards optimizer state and gradients across data parallel ranks? [YES/no]: ",
605
+ _convert_yes_no_to_bool,
606
+ default=True,
607
+ error_message="Please enter yes or no.",
608
+ )
609
+
610
+ megatron_lm_config[prefix + "gradient_clipping"] = _ask_field(
611
+ "What is the gradient clipping value based on global L2 Norm (0 to disable)? [1.0]: ",
612
+ float,
613
+ default=1.0,
614
+ )
615
+ # TPU specific defaults
616
+ tpu_commands = None
617
+ tpu_command_file = None
618
+ tpu_downcast_bf16 = "no"
619
+ tpu_env = []
620
+ tpu_name = None
621
+ tpu_vm = None
622
+ tpu_zone = None
623
+ tpu_use_sudo = False
624
+ tpu_use_cluster = False
625
+
626
+ if distributed_type in [
627
+ DistributedType.MULTI_CPU,
628
+ DistributedType.MULTI_XPU,
629
+ DistributedType.MULTI_HPU,
630
+ DistributedType.MULTI_GPU,
631
+ DistributedType.MULTI_MLU,
632
+ DistributedType.MULTI_SDAA,
633
+ DistributedType.MULTI_MUSA,
634
+ DistributedType.MULTI_NPU,
635
+ DistributedType.XLA,
636
+ ]:
637
+ machine_type = str(distributed_type).split(".")[1].replace("MULTI_", "")
638
+ if machine_type == "TPU":
639
+ machine_type += " cores"
640
+ elif machine_type == "CPU":
641
+ machine_type = "processes"
642
+ else:
643
+ machine_type += "(s)"
644
+ num_processes = _ask_field(
645
+ f"How many {machine_type} should be used for distributed training? [1]:",
646
+ int,
647
+ default=1,
648
+ error_message="Please enter an integer.",
649
+ )
650
+ elif distributed_type in [DistributedType.FSDP, DistributedType.DEEPSPEED, DistributedType.MEGATRON_LM]:
651
+ num_processes = _ask_field(
652
+ "How many GPU(s) should be used for distributed training? [1]:",
653
+ int,
654
+ default=1,
655
+ error_message="Please enter an integer.",
656
+ )
657
+ else:
658
+ num_processes = 1
659
+
660
+ if (distributed_type == DistributedType.MULTI_GPU) and (num_machines == 1) and (num_processes == 1):
661
+ raise ValueError(
662
+ 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."
663
+ )
664
+
665
+ if (
666
+ distributed_type
667
+ in [
668
+ DistributedType.MULTI_GPU,
669
+ DistributedType.MULTI_MLU,
670
+ DistributedType.MULTI_SDAA,
671
+ DistributedType.MULTI_MUSA,
672
+ DistributedType.MULTI_NPU,
673
+ DistributedType.MULTI_XPU,
674
+ DistributedType.MULTI_HPU,
675
+ DistributedType.NO,
676
+ ]
677
+ and not use_cpu
678
+ and not use_mps
679
+ ):
680
+ if is_npu_available():
681
+ machine_type = "NPU(s)"
682
+ elif is_mlu_available():
683
+ machine_type = "MLU(s)"
684
+ elif is_sdaa_available():
685
+ machine_type = "SDAA(s)"
686
+ elif is_musa_available():
687
+ machine_type = "MUSA(s)"
688
+ elif is_xpu_available():
689
+ machine_type = "XPU(s)"
690
+ elif is_hpu_available():
691
+ machine_type = "HPU(s)"
692
+ else:
693
+ machine_type = "GPU(s)"
694
+ gpu_ids = _ask_field(
695
+ f"What {machine_type} (by id) should be used for training on this machine as a comma-separated list? [all]:",
696
+ default="all",
697
+ )
698
+
699
+ # CPU affinity is only supported on NVIDIA hardware for now
700
+ enable_cpu_affinity = False
701
+ if distributed_type in (DistributedType.NO, DistributedType.MULTI_GPU) and not use_cpu and not use_mps:
702
+ enable_cpu_affinity = _ask_field(
703
+ "Would you like to enable numa efficiency? (Currently only supported on NVIDIA hardware). [yes/NO]: ",
704
+ _convert_yes_no_to_bool,
705
+ default=False,
706
+ error_message="Please enter yes or no.",
707
+ )
708
+
709
+ fp8_config = None
710
+ if distributed_type == DistributedType.XLA:
711
+ mixed_precision = "no"
712
+ main_training_function = _ask_field(
713
+ "What is the name of the function in your script that should be launched in all parallel scripts? [main]: ",
714
+ default="main",
715
+ )
716
+ tpu_use_cluster = _ask_field(
717
+ "Are you using a TPU cluster? [yes/NO]: ",
718
+ _convert_yes_no_to_bool,
719
+ default=False,
720
+ error_message="Please enter yes or no.",
721
+ )
722
+ if tpu_use_cluster:
723
+ tpu_name = _ask_field(
724
+ "What is the name of your TPU cluster? ",
725
+ default=None,
726
+ error_message="Please enter the name of your TPU cluster.",
727
+ )
728
+ tpu_zone = _ask_field(
729
+ "What is the zone of your TPU cluster? ",
730
+ default=None,
731
+ error_message="Please enter the zone of your TPU cluster.",
732
+ )
733
+ tpu_use_sudo = _ask_field(
734
+ "To run a python script in a TPU pod, should `sudo` be used? [yes/NO]: ",
735
+ default=False,
736
+ error_message="Please enter yes or no.",
737
+ )
738
+ run_commands = _ask_field(
739
+ "Do you have code you wish to run on startup in each pod? [yes/NO]: ",
740
+ _convert_yes_no_to_bool,
741
+ default=False,
742
+ error_message="Please enter yes or no.",
743
+ )
744
+ if run_commands:
745
+ use_command_file = _ask_field(
746
+ "Is this code located in a bash script? [yes/NO]: ",
747
+ _convert_yes_no_to_bool,
748
+ default=False,
749
+ error_message="Please enter yes or no.",
750
+ )
751
+ if use_command_file:
752
+ tpu_command_file = _ask_field(
753
+ "What is the path to your bash script? ",
754
+ default=None,
755
+ error_message="Please enter the path to your bash script.",
756
+ )
757
+ tpu_command_file = os.path.abspath(tpu_command_file)
758
+ else:
759
+ print("Please enter each command separately you wish to run on startup in each pod.")
760
+ tpu_commands = []
761
+ another_command = True
762
+ while another_command:
763
+ tpu_commands.append(
764
+ _ask_field(
765
+ "Please enter a single command to be ran ",
766
+ default=None,
767
+ error_message="Please enter the commands you wish to run on startup in each pod as a single string.",
768
+ )
769
+ )
770
+ another_command = _ask_field(
771
+ "Do you wish to add another command? [yes/NO]: ",
772
+ _convert_yes_no_to_bool,
773
+ default=False,
774
+ error_message="Please enter yes or no.",
775
+ )
776
+ tpu_vm = _ask_field(
777
+ "If not using an instance group, what are the names of the Compute VM instances to be used, separated by a comma: ",
778
+ default="",
779
+ ).split(",")
780
+ tpu_env = _ask_field(
781
+ "What environment variables do you wish to set in each pod, separated by a comma: ",
782
+ default="",
783
+ ).split(",")
784
+
785
+ else:
786
+ main_training_function = "main"
787
+ if distributed_type == DistributedType.DEEPSPEED and use_deepspeed_config:
788
+ mixed_precision = None
789
+ else:
790
+ mixed_precision = _ask_options(
791
+ "Do you wish to use mixed precision?",
792
+ ["no", "fp16", "bf16", "fp8"],
793
+ _convert_mixed_precision,
794
+ )
795
+ if mixed_precision == "fp8":
796
+ if not is_fp8_available():
797
+ raise ValueError("FP8 (either Transformer Engine or MSAMP) is not installed on this machine.")
798
+ fp8_config = {}
799
+ fp8_config["backend"] = _ask_options(
800
+ "Which FP8 backend do you want to use?",
801
+ ["te", "msamp"],
802
+ _convert_fp8_backend,
803
+ )
804
+ if fp8_config["backend"] == "TE":
805
+ if not is_transformer_engine_available():
806
+ raise ValueError("TransformersEngine was selected, but it is not installed on this machine.")
807
+ fp8_config["use_autocast_during_eval"] = _ask_field(
808
+ "Do you want to use FP8 autocast during eval mode? Generally better metrics are found when this is disabled [yes/NO]: ",
809
+ _convert_yes_no_to_bool,
810
+ default=False,
811
+ )
812
+ fp8_config["margin"] = _ask_field(
813
+ "What margin should be used for gradient scaling? [0]: ",
814
+ int,
815
+ default=0,
816
+ )
817
+ fp8_config["interval"] = _ask_field(
818
+ "What interval should be used for for how often the scaling factor is recomputed? [1]: ",
819
+ int,
820
+ default=1,
821
+ )
822
+ fp8_config["fp8_format"] = _ask_options(
823
+ "Which weight format should be used?",
824
+ ["HYBRID", "E4M3", "E5M2"],
825
+ lambda i: ["HYBRID", "E4M3", "E5M2"][i],
826
+ default=0,
827
+ )
828
+ fp8_config["amax_history_length"] = _ask_field(
829
+ "What length of history should be used for the amax scaling factor computation? [1024]: ",
830
+ int,
831
+ default=1024,
832
+ )
833
+ fp8_config["amax_compute_algorithm"] = _ask_options(
834
+ "Which algorithm should be used for the amax scaling factor computation?",
835
+ ["max", "most_recent"],
836
+ lambda x: "max" if x == 0 else "most_recent",
837
+ default=0,
838
+ )
839
+ fp8_config["override_linear_precision"] = _ask_field(
840
+ "Do you want to to execute `fprop`, `dgrad`, and `wgrad` GEMMS in higher precision? [yes/NO]: ",
841
+ _convert_yes_no_to_bool,
842
+ default=False,
843
+ )
844
+ if fp8_config["override_linear_precision"]:
845
+ fprop = _ask_field(
846
+ "Should `fprop` be executed in higher precision? [yes/NO]: ",
847
+ _convert_yes_no_to_bool,
848
+ default=False,
849
+ )
850
+ dgrad = _ask_field(
851
+ "Should `dgrad` be executed in higher precision? [yes/NO]: ",
852
+ _convert_yes_no_to_bool,
853
+ default=False,
854
+ )
855
+ wgrad = _ask_field(
856
+ "Should `wgrad` be executed in higher precision? [yes/NO]: ",
857
+ _convert_yes_no_to_bool,
858
+ default=False,
859
+ )
860
+ fp8_config["override_linear_precision"] = (fprop, dgrad, wgrad)
861
+ else:
862
+ fp8_config["override_linear_precision"] = (False, False, False)
863
+
864
+ elif fp8_config["backend"] == "MSAMP":
865
+ if not is_msamp_available():
866
+ raise ValueError("MSAMP was selected, but it is not installed on this machine.")
867
+ fp8_config["optimization_level"] = _ask_options(
868
+ "Which optimization level should be used?",
869
+ ["O1", "O2"],
870
+ lambda x: "O1" if x == 0 else "O2",
871
+ default=1,
872
+ )
873
+
874
+ if use_dynamo and mixed_precision == "no" and not use_cpu:
875
+ print(
876
+ "Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts."
877
+ )
878
+
879
+ if distributed_type == DistributedType.XLA and mixed_precision == "bf16":
880
+ tpu_downcast_bf16 = _ask_field(
881
+ "Should `torch.float` be cast as `bfloat16` and `torch.double` remain `float32` on TPUs?", default="no"
882
+ )
883
+
884
+ return ClusterConfig(
885
+ compute_environment=ComputeEnvironment.LOCAL_MACHINE,
886
+ distributed_type=distributed_type,
887
+ num_processes=num_processes,
888
+ gpu_ids=gpu_ids,
889
+ mixed_precision=mixed_precision,
890
+ downcast_bf16=tpu_downcast_bf16,
891
+ machine_rank=machine_rank,
892
+ num_machines=num_machines,
893
+ main_process_ip=main_process_ip,
894
+ main_process_port=main_process_port,
895
+ main_training_function=main_training_function,
896
+ fp8_config=fp8_config,
897
+ deepspeed_config=deepspeed_config,
898
+ fsdp_config=fsdp_config,
899
+ parallelism_config=parallelism_config,
900
+ megatron_lm_config=megatron_lm_config,
901
+ ipex_config=ipex_config,
902
+ mpirun_config=mpirun_config,
903
+ use_cpu=use_cpu,
904
+ rdzv_backend=rdzv_backend,
905
+ same_network=same_network,
906
+ commands=tpu_commands,
907
+ command_file=tpu_command_file,
908
+ tpu_env=tpu_env,
909
+ tpu_name=tpu_name,
910
+ tpu_vm=tpu_vm,
911
+ tpu_zone=tpu_zone,
912
+ tpu_use_sudo=tpu_use_sudo,
913
+ tpu_use_cluster=tpu_use_cluster,
914
+ dynamo_config=dynamo_config,
915
+ debug=debug,
916
+ enable_cpu_affinity=enable_cpu_affinity,
917
+ )
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/config.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2021 The HuggingFace Team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import argparse
18
+ import os
19
+
20
+ from accelerate.utils import ComputeEnvironment
21
+
22
+ from .cluster import get_cluster_input
23
+ from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401
24
+ from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401
25
+ from .sagemaker import get_sagemaker_input
26
+
27
+
28
+ 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"
29
+
30
+
31
+ def get_user_input():
32
+ compute_environment = _ask_options(
33
+ "In which compute environment are you running?",
34
+ ["This machine", "AWS (Amazon SageMaker)"],
35
+ _convert_compute_environment,
36
+ )
37
+ if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
38
+ config = get_sagemaker_input()
39
+ else:
40
+ config = get_cluster_input()
41
+ return config
42
+
43
+
44
+ def config_command_parser(subparsers=None):
45
+ if subparsers is not None:
46
+ parser = subparsers.add_parser("config", description=description)
47
+ else:
48
+ parser = argparse.ArgumentParser("Accelerate config command", description=description)
49
+
50
+ parser.add_argument(
51
+ "--config_file",
52
+ default=None,
53
+ help=(
54
+ "The path to use to store the config file. Will default to a file named default_config.yaml in the cache "
55
+ "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have "
56
+ "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed "
57
+ "with 'huggingface'."
58
+ ),
59
+ )
60
+
61
+ if subparsers is not None:
62
+ parser.set_defaults(func=config_command)
63
+ return parser
64
+
65
+
66
+ def config_command(args):
67
+ config = get_user_input()
68
+ if args.config_file is not None:
69
+ config_file = args.config_file
70
+ else:
71
+ if not os.path.isdir(cache_dir):
72
+ os.makedirs(cache_dir)
73
+ config_file = default_yaml_config_file
74
+
75
+ if config_file.endswith(".json"):
76
+ config.to_json_file(config_file)
77
+ else:
78
+ config.to_yaml_file(config_file)
79
+ print(f"accelerate configuration saved at {config_file}")
80
+
81
+
82
+ def main():
83
+ parser = config_command_parser()
84
+ args = parser.parse_args()
85
+ config_command(args)
86
+
87
+
88
+ if __name__ == "__main__":
89
+ main()
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/config_args.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2021 The HuggingFace Team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import json
18
+ import os
19
+ from dataclasses import dataclass
20
+ from enum import Enum
21
+ from typing import Optional, Union
22
+
23
+ import yaml
24
+
25
+ from ...utils import ComputeEnvironment, DistributedType, SageMakerDistributedType
26
+ from ...utils.constants import SAGEMAKER_PYTHON_VERSION, SAGEMAKER_PYTORCH_VERSION, SAGEMAKER_TRANSFORMERS_VERSION
27
+
28
+
29
+ hf_cache_home = os.path.expanduser(
30
+ os.environ.get("HF_HOME", os.path.join(os.environ.get("XDG_CACHE_HOME", "~/.cache"), "huggingface"))
31
+ )
32
+ cache_dir = os.path.join(hf_cache_home, "accelerate")
33
+ default_json_config_file = os.path.join(cache_dir, "default_config.yaml")
34
+ default_yaml_config_file = os.path.join(cache_dir, "default_config.yaml")
35
+
36
+ # For backward compatibility: the default config is the json one if it's the only existing file.
37
+ if os.path.isfile(default_yaml_config_file) or not os.path.isfile(default_json_config_file):
38
+ default_config_file = default_yaml_config_file
39
+ else:
40
+ default_config_file = default_json_config_file
41
+
42
+
43
+ def load_config_from_file(config_file):
44
+ if config_file is not None:
45
+ if not os.path.isfile(config_file):
46
+ raise FileNotFoundError(
47
+ f"The passed configuration file `{config_file}` does not exist. "
48
+ "Please pass an existing file to `accelerate launch`, or use the default one "
49
+ "created through `accelerate config` and run `accelerate launch` "
50
+ "without the `--config_file` argument."
51
+ )
52
+ else:
53
+ config_file = default_config_file
54
+ with open(config_file, encoding="utf-8") as f:
55
+ if config_file.endswith(".json"):
56
+ if (
57
+ json.load(f).get("compute_environment", ComputeEnvironment.LOCAL_MACHINE)
58
+ == ComputeEnvironment.LOCAL_MACHINE
59
+ ):
60
+ config_class = ClusterConfig
61
+ else:
62
+ config_class = SageMakerConfig
63
+ return config_class.from_json_file(json_file=config_file)
64
+ else:
65
+ if (
66
+ yaml.safe_load(f).get("compute_environment", ComputeEnvironment.LOCAL_MACHINE)
67
+ == ComputeEnvironment.LOCAL_MACHINE
68
+ ):
69
+ config_class = ClusterConfig
70
+ else:
71
+ config_class = SageMakerConfig
72
+ return config_class.from_yaml_file(yaml_file=config_file)
73
+
74
+
75
+ @dataclass
76
+ class BaseConfig:
77
+ compute_environment: ComputeEnvironment
78
+ distributed_type: Union[DistributedType, SageMakerDistributedType]
79
+ mixed_precision: str
80
+ use_cpu: bool
81
+ debug: bool
82
+
83
+ def to_dict(self):
84
+ result = self.__dict__
85
+ # For serialization, it's best to convert Enums to strings (or their underlying value type).
86
+
87
+ def _convert_enums(value):
88
+ if isinstance(value, Enum):
89
+ return value.value
90
+ if isinstance(value, dict):
91
+ if not bool(value):
92
+ return None
93
+ for key1, value1 in value.items():
94
+ value[key1] = _convert_enums(value1)
95
+ return value
96
+
97
+ for key, value in result.items():
98
+ result[key] = _convert_enums(value)
99
+ result = {k: v for k, v in result.items() if v is not None}
100
+ return result
101
+
102
+ @staticmethod
103
+ def process_config(config_dict):
104
+ """
105
+ Processes `config_dict` and sets default values for any missing keys
106
+ """
107
+ if "compute_environment" not in config_dict:
108
+ config_dict["compute_environment"] = ComputeEnvironment.LOCAL_MACHINE
109
+ if "distributed_type" not in config_dict:
110
+ raise ValueError("A `distributed_type` must be specified in the config file.")
111
+ if "num_processes" not in config_dict and config_dict["distributed_type"] == DistributedType.NO:
112
+ config_dict["num_processes"] = 1
113
+ if "mixed_precision" not in config_dict:
114
+ config_dict["mixed_precision"] = "fp16" if ("fp16" in config_dict and config_dict["fp16"]) else None
115
+ if "fp16" in config_dict: # Convert the config to the new format.
116
+ del config_dict["fp16"]
117
+ if "dynamo_backend" in config_dict: # Convert the config to the new format.
118
+ dynamo_backend = config_dict.pop("dynamo_backend")
119
+ config_dict["dynamo_config"] = {} if dynamo_backend == "NO" else {"dynamo_backend": dynamo_backend}
120
+ if "use_cpu" not in config_dict:
121
+ config_dict["use_cpu"] = False
122
+ if "debug" not in config_dict:
123
+ config_dict["debug"] = False
124
+ if "enable_cpu_affinity" not in config_dict:
125
+ config_dict["enable_cpu_affinity"] = False
126
+ return config_dict
127
+
128
+ @classmethod
129
+ def from_json_file(cls, json_file=None):
130
+ json_file = default_json_config_file if json_file is None else json_file
131
+ with open(json_file, encoding="utf-8") as f:
132
+ config_dict = json.load(f)
133
+ config_dict = cls.process_config(config_dict)
134
+ extra_keys = sorted(set(config_dict.keys()) - set(cls.__dataclass_fields__.keys()))
135
+ if len(extra_keys) > 0:
136
+ raise ValueError(
137
+ f"The config file at {json_file} had unknown keys ({extra_keys}), please try upgrading your `accelerate`"
138
+ " version or fix (and potentially remove) these keys from your config file."
139
+ )
140
+
141
+ return cls(**config_dict)
142
+
143
+ def to_json_file(self, json_file):
144
+ with open(json_file, "w", encoding="utf-8") as f:
145
+ content = json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n"
146
+ f.write(content)
147
+
148
+ @classmethod
149
+ def from_yaml_file(cls, yaml_file=None):
150
+ yaml_file = default_yaml_config_file if yaml_file is None else yaml_file
151
+ with open(yaml_file, encoding="utf-8") as f:
152
+ config_dict = yaml.safe_load(f)
153
+ config_dict = cls.process_config(config_dict)
154
+ extra_keys = sorted(set(config_dict.keys()) - set(cls.__dataclass_fields__.keys()))
155
+ if len(extra_keys) > 0:
156
+ raise ValueError(
157
+ f"The config file at {yaml_file} had unknown keys ({extra_keys}), please try upgrading your `accelerate`"
158
+ " version or fix (and potentially remove) these keys from your config file."
159
+ )
160
+ return cls(**config_dict)
161
+
162
+ def to_yaml_file(self, yaml_file):
163
+ with open(yaml_file, "w", encoding="utf-8") as f:
164
+ yaml.safe_dump(self.to_dict(), f)
165
+
166
+ def __post_init__(self):
167
+ if isinstance(self.compute_environment, str):
168
+ self.compute_environment = ComputeEnvironment(self.compute_environment)
169
+ if isinstance(self.distributed_type, str):
170
+ if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
171
+ self.distributed_type = SageMakerDistributedType(self.distributed_type)
172
+ else:
173
+ self.distributed_type = DistributedType(self.distributed_type)
174
+ if getattr(self, "dynamo_config", None) is None:
175
+ self.dynamo_config = {}
176
+
177
+
178
+ @dataclass
179
+ class ClusterConfig(BaseConfig):
180
+ num_processes: int = -1 # For instance if we use SLURM and the user manually passes it in
181
+ machine_rank: int = 0
182
+ num_machines: int = 1
183
+ gpu_ids: Optional[str] = None
184
+ main_process_ip: Optional[str] = None
185
+ main_process_port: Optional[int] = None
186
+ rdzv_backend: Optional[str] = "static"
187
+ same_network: Optional[bool] = False
188
+ main_training_function: str = "main"
189
+ enable_cpu_affinity: bool = False
190
+
191
+ # args for FP8 training
192
+ fp8_config: dict = None
193
+ # args for deepspeed_plugin
194
+ deepspeed_config: dict = None
195
+ # args for fsdp
196
+ fsdp_config: dict = None
197
+ # args for parallelism config
198
+ parallelism_config: dict = None
199
+ # args for megatron_lm
200
+ megatron_lm_config: dict = None
201
+ # args for ipex
202
+ ipex_config: dict = None
203
+ # args for mpirun
204
+ mpirun_config: dict = None
205
+ # args for TPU
206
+ downcast_bf16: bool = False
207
+
208
+ # args for TPU pods
209
+ tpu_name: str = None
210
+ tpu_zone: str = None
211
+ tpu_use_cluster: bool = False
212
+ tpu_use_sudo: bool = False
213
+ command_file: str = None
214
+ commands: list[str] = None
215
+ tpu_vm: list[str] = None
216
+ tpu_env: list[str] = None
217
+
218
+ # args for dynamo
219
+ dynamo_config: dict = None
220
+
221
+ def __post_init__(self):
222
+ if self.deepspeed_config is None:
223
+ self.deepspeed_config = {}
224
+ if self.fsdp_config is None:
225
+ self.fsdp_config = {}
226
+ if self.megatron_lm_config is None:
227
+ self.megatron_lm_config = {}
228
+ if self.ipex_config is None:
229
+ self.ipex_config = {}
230
+ if self.mpirun_config is None:
231
+ self.mpirun_config = {}
232
+ if self.fp8_config is None:
233
+ self.fp8_config = {}
234
+ if self.parallelism_config is None:
235
+ self.parallelism_config = {}
236
+ return super().__post_init__()
237
+
238
+
239
+ @dataclass
240
+ class SageMakerConfig(BaseConfig):
241
+ ec2_instance_type: str
242
+ iam_role_name: str
243
+ image_uri: Optional[str] = None
244
+ profile: Optional[str] = None
245
+ region: str = "us-east-1"
246
+ num_machines: int = 1
247
+ gpu_ids: str = "all"
248
+ base_job_name: str = f"accelerate-sagemaker-{num_machines}"
249
+ pytorch_version: str = SAGEMAKER_PYTORCH_VERSION
250
+ transformers_version: str = SAGEMAKER_TRANSFORMERS_VERSION
251
+ py_version: str = SAGEMAKER_PYTHON_VERSION
252
+ sagemaker_inputs_file: str = None
253
+ sagemaker_metrics_file: str = None
254
+ additional_args: dict = None
255
+ dynamo_config: dict = None
256
+ enable_cpu_affinity: bool = False
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/config_utils.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2021 The HuggingFace Team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import argparse
18
+
19
+ from ...utils.dataclasses import (
20
+ ComputeEnvironment,
21
+ DistributedType,
22
+ DynamoBackend,
23
+ FP8BackendType,
24
+ PrecisionType,
25
+ SageMakerDistributedType,
26
+ )
27
+ from ..menu import BulletMenu
28
+
29
+
30
+ DYNAMO_BACKENDS = [
31
+ "EAGER",
32
+ "AOT_EAGER",
33
+ "INDUCTOR",
34
+ "AOT_TS_NVFUSER",
35
+ "NVPRIMS_NVFUSER",
36
+ "CUDAGRAPHS",
37
+ "OFI",
38
+ "FX2TRT",
39
+ "ONNXRT",
40
+ "TENSORRT",
41
+ "AOT_TORCHXLA_TRACE_ONCE",
42
+ "TORHCHXLA_TRACE_ONCE",
43
+ "IPEX",
44
+ "TVM",
45
+ ]
46
+
47
+
48
+ def _ask_field(input_text, convert_value=None, default=None, error_message=None):
49
+ ask_again = True
50
+ while ask_again:
51
+ result = input(input_text)
52
+ try:
53
+ if default is not None and len(result) == 0:
54
+ return default
55
+ return convert_value(result) if convert_value is not None else result
56
+ except Exception:
57
+ if error_message is not None:
58
+ print(error_message)
59
+
60
+
61
+ def _ask_options(input_text, options=[], convert_value=None, default=0):
62
+ menu = BulletMenu(input_text, options)
63
+ result = menu.run(default_choice=default)
64
+ return convert_value(result) if convert_value is not None else result
65
+
66
+
67
+ def _convert_compute_environment(value):
68
+ value = int(value)
69
+ return ComputeEnvironment(["LOCAL_MACHINE", "AMAZON_SAGEMAKER"][value])
70
+
71
+
72
+ def _convert_distributed_mode(value):
73
+ value = int(value)
74
+ return DistributedType(
75
+ [
76
+ "NO",
77
+ "MULTI_CPU",
78
+ "MULTI_XPU",
79
+ "MULTI_HPU",
80
+ "MULTI_GPU",
81
+ "MULTI_NPU",
82
+ "MULTI_MLU",
83
+ "MULTI_SDAA",
84
+ "MULTI_MUSA",
85
+ "XLA",
86
+ ][value]
87
+ )
88
+
89
+
90
+ def _convert_dynamo_backend(value):
91
+ value = int(value)
92
+ return DynamoBackend(DYNAMO_BACKENDS[value]).value
93
+
94
+
95
+ def _convert_mixed_precision(value):
96
+ value = int(value)
97
+ return PrecisionType(["no", "fp16", "bf16", "fp8"][value])
98
+
99
+
100
+ def _convert_sagemaker_distributed_mode(value):
101
+ value = int(value)
102
+ return SageMakerDistributedType(["NO", "DATA_PARALLEL", "MODEL_PARALLEL"][value])
103
+
104
+
105
+ def _convert_fp8_backend(value):
106
+ value = int(value)
107
+ return FP8BackendType(["TE", "MSAMP"][value])
108
+
109
+
110
+ def _convert_yes_no_to_bool(value):
111
+ return {"yes": True, "no": False}[value.lower()]
112
+
113
+
114
+ class SubcommandHelpFormatter(argparse.RawDescriptionHelpFormatter):
115
+ """
116
+ A custom formatter that will remove the usage line from the help message for subcommands.
117
+ """
118
+
119
+ def _format_usage(self, usage, actions, groups, prefix):
120
+ usage = super()._format_usage(usage, actions, groups, prefix)
121
+ usage = usage.replace("<command> [<args>] ", "")
122
+ return usage
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/default.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2021 The HuggingFace Team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ from pathlib import Path
18
+
19
+ import torch
20
+
21
+ from ...utils import (
22
+ is_hpu_available,
23
+ is_mlu_available,
24
+ is_musa_available,
25
+ is_npu_available,
26
+ is_sdaa_available,
27
+ is_xpu_available,
28
+ )
29
+ from .config_args import ClusterConfig, default_json_config_file
30
+ from .config_utils import SubcommandHelpFormatter
31
+
32
+
33
+ description = "Create a default config file for Accelerate with only a few flags set."
34
+
35
+
36
+ def write_basic_config(mixed_precision="no", save_location: str = default_json_config_file):
37
+ """
38
+ Creates and saves a basic cluster config to be used on a local machine with potentially multiple GPUs. Will also
39
+ set CPU if it is a CPU-only machine.
40
+
41
+ Args:
42
+ mixed_precision (`str`, *optional*, defaults to "no"):
43
+ Mixed Precision to use. Should be one of "no", "fp16", or "bf16"
44
+ save_location (`str`, *optional*, defaults to `default_json_config_file`):
45
+ Optional custom save location. Should be passed to `--config_file` when using `accelerate launch`. Default
46
+ location is inside the huggingface cache folder (`~/.cache/huggingface`) but can be overridden by setting
47
+ the `HF_HOME` environmental variable, followed by `accelerate/default_config.yaml`.
48
+ """
49
+ path = Path(save_location)
50
+ path.parent.mkdir(parents=True, exist_ok=True)
51
+ if path.exists():
52
+ print(
53
+ f"Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`."
54
+ )
55
+ return False
56
+ mixed_precision = mixed_precision.lower()
57
+ if mixed_precision not in ["no", "fp16", "bf16", "fp8"]:
58
+ raise ValueError(
59
+ f"`mixed_precision` should be one of 'no', 'fp16', 'bf16', or 'fp8'. Received {mixed_precision}"
60
+ )
61
+ config = {
62
+ "compute_environment": "LOCAL_MACHINE",
63
+ "mixed_precision": mixed_precision,
64
+ }
65
+ if is_mlu_available():
66
+ num_mlus = torch.mlu.device_count()
67
+ config["num_processes"] = num_mlus
68
+ config["use_cpu"] = False
69
+ if num_mlus > 1:
70
+ config["distributed_type"] = "MULTI_MLU"
71
+ else:
72
+ config["distributed_type"] = "NO"
73
+ if is_sdaa_available():
74
+ num_sdaas = torch.sdaa.device_count()
75
+ config["num_processes"] = num_sdaas
76
+ config["use_cpu"] = False
77
+ if num_sdaas > 1:
78
+ config["distributed_type"] = "MULTI_SDAA"
79
+ else:
80
+ config["distributed_type"] = "NO"
81
+ elif is_musa_available():
82
+ num_musas = torch.musa.device_count()
83
+ config["num_processes"] = num_musas
84
+ config["use_cpu"] = False
85
+ if num_musas > 1:
86
+ config["distributed_type"] = "MULTI_MUSA"
87
+ else:
88
+ config["distributed_type"] = "NO"
89
+ elif is_hpu_available():
90
+ num_hpus = torch.hpu.device_count()
91
+ config["num_processes"] = num_hpus
92
+ config["use_cpu"] = False
93
+ if num_hpus > 1:
94
+ config["distributed_type"] = "MULTI_HPU"
95
+ else:
96
+ config["distributed_type"] = "NO"
97
+ elif torch.cuda.is_available():
98
+ num_gpus = torch.cuda.device_count()
99
+ config["num_processes"] = num_gpus
100
+ config["use_cpu"] = False
101
+ if num_gpus > 1:
102
+ config["distributed_type"] = "MULTI_GPU"
103
+ else:
104
+ config["distributed_type"] = "NO"
105
+ elif is_xpu_available():
106
+ num_xpus = torch.xpu.device_count()
107
+ config["num_processes"] = num_xpus
108
+ config["use_cpu"] = False
109
+ if num_xpus > 1:
110
+ config["distributed_type"] = "MULTI_XPU"
111
+ else:
112
+ config["distributed_type"] = "NO"
113
+ elif is_npu_available():
114
+ num_npus = torch.npu.device_count()
115
+ config["num_processes"] = num_npus
116
+ config["use_cpu"] = False
117
+ if num_npus > 1:
118
+ config["distributed_type"] = "MULTI_NPU"
119
+ else:
120
+ config["distributed_type"] = "NO"
121
+ else:
122
+ num_xpus = 0
123
+ config["use_cpu"] = True
124
+ config["num_processes"] = 1
125
+ config["distributed_type"] = "NO"
126
+ config["debug"] = False
127
+ config["enable_cpu_affinity"] = False
128
+ config = ClusterConfig(**config)
129
+ config.to_json_file(path)
130
+ return path
131
+
132
+
133
+ def default_command_parser(parser, parents):
134
+ parser = parser.add_parser("default", parents=parents, help=description, formatter_class=SubcommandHelpFormatter)
135
+ parser.add_argument(
136
+ "--config_file",
137
+ default=default_json_config_file,
138
+ help=(
139
+ "The path to use to store the config file. Will default to a file named default_config.yaml in the cache "
140
+ "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have "
141
+ "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed "
142
+ "with 'huggingface'."
143
+ ),
144
+ dest="save_location",
145
+ )
146
+
147
+ parser.add_argument(
148
+ "--mixed_precision",
149
+ choices=["no", "fp16", "bf16"],
150
+ type=str,
151
+ help="Whether or not to use mixed precision training. "
152
+ "Choose between FP16 and BF16 (bfloat16) training. "
153
+ "BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.",
154
+ default="no",
155
+ )
156
+ parser.set_defaults(func=default_config_command)
157
+ return parser
158
+
159
+
160
+ def default_config_command(args):
161
+ config_file = write_basic_config(args.mixed_precision, args.save_location)
162
+ if config_file:
163
+ print(f"accelerate configuration saved at {config_file}")
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/sagemaker.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2021 The HuggingFace Team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ import json
17
+ import os
18
+
19
+ from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES
20
+ from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType
21
+ from ...utils.imports import is_boto3_available
22
+ from .config_args import SageMakerConfig
23
+ from .config_utils import (
24
+ DYNAMO_BACKENDS,
25
+ _ask_field,
26
+ _ask_options,
27
+ _convert_dynamo_backend,
28
+ _convert_mixed_precision,
29
+ _convert_sagemaker_distributed_mode,
30
+ _convert_yes_no_to_bool,
31
+ )
32
+
33
+
34
+ if is_boto3_available():
35
+ import boto3 # noqa: F401
36
+
37
+
38
+ def _create_iam_role_for_sagemaker(role_name):
39
+ iam_client = boto3.client("iam")
40
+
41
+ sagemaker_trust_policy = {
42
+ "Version": "2012-10-17",
43
+ "Statement": [
44
+ {"Effect": "Allow", "Principal": {"Service": "sagemaker.amazonaws.com"}, "Action": "sts:AssumeRole"}
45
+ ],
46
+ }
47
+ try:
48
+ # create the role, associated with the chosen trust policy
49
+ iam_client.create_role(
50
+ RoleName=role_name, AssumeRolePolicyDocument=json.dumps(sagemaker_trust_policy, indent=2)
51
+ )
52
+ policy_document = {
53
+ "Version": "2012-10-17",
54
+ "Statement": [
55
+ {
56
+ "Effect": "Allow",
57
+ "Action": [
58
+ "sagemaker:*",
59
+ "ecr:GetDownloadUrlForLayer",
60
+ "ecr:BatchGetImage",
61
+ "ecr:BatchCheckLayerAvailability",
62
+ "ecr:GetAuthorizationToken",
63
+ "cloudwatch:PutMetricData",
64
+ "cloudwatch:GetMetricData",
65
+ "cloudwatch:GetMetricStatistics",
66
+ "cloudwatch:ListMetrics",
67
+ "logs:CreateLogGroup",
68
+ "logs:CreateLogStream",
69
+ "logs:DescribeLogStreams",
70
+ "logs:PutLogEvents",
71
+ "logs:GetLogEvents",
72
+ "s3:CreateBucket",
73
+ "s3:ListBucket",
74
+ "s3:GetBucketLocation",
75
+ "s3:GetObject",
76
+ "s3:PutObject",
77
+ ],
78
+ "Resource": "*",
79
+ }
80
+ ],
81
+ }
82
+ # attach policy to role
83
+ iam_client.put_role_policy(
84
+ RoleName=role_name,
85
+ PolicyName=f"{role_name}_policy_permission",
86
+ PolicyDocument=json.dumps(policy_document, indent=2),
87
+ )
88
+ except iam_client.exceptions.EntityAlreadyExistsException:
89
+ print(f"role {role_name} already exists. Using existing one")
90
+
91
+
92
+ def _get_iam_role_arn(role_name):
93
+ iam_client = boto3.client("iam")
94
+ return iam_client.get_role(RoleName=role_name)["Role"]["Arn"]
95
+
96
+
97
+ def get_sagemaker_input():
98
+ credentials_configuration = _ask_options(
99
+ "How do you want to authorize?",
100
+ ["AWS Profile", "Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) "],
101
+ int,
102
+ )
103
+ aws_profile = None
104
+ if credentials_configuration == 0:
105
+ aws_profile = _ask_field("Enter your AWS Profile name: [default] ", default="default")
106
+ os.environ["AWS_PROFILE"] = aws_profile
107
+ else:
108
+ print(
109
+ "Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,"
110
+ "`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`"
111
+ )
112
+ aws_access_key_id = _ask_field("AWS Access Key ID: ")
113
+ os.environ["AWS_ACCESS_KEY_ID"] = aws_access_key_id
114
+
115
+ aws_secret_access_key = _ask_field("AWS Secret Access Key: ")
116
+ os.environ["AWS_SECRET_ACCESS_KEY"] = aws_secret_access_key
117
+
118
+ aws_region = _ask_field("Enter your AWS Region: [us-east-1]", default="us-east-1")
119
+ os.environ["AWS_DEFAULT_REGION"] = aws_region
120
+
121
+ role_management = _ask_options(
122
+ "Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?",
123
+ ["Provide IAM Role name", "Create new IAM role using credentials"],
124
+ int,
125
+ )
126
+ if role_management == 0:
127
+ iam_role_name = _ask_field("Enter your IAM role name: ")
128
+ else:
129
+ iam_role_name = "accelerate_sagemaker_execution_role"
130
+ print(f'Accelerate will create an iam role "{iam_role_name}" using the provided credentials')
131
+ _create_iam_role_for_sagemaker(iam_role_name)
132
+
133
+ is_custom_docker_image = _ask_field(
134
+ "Do you want to use custom Docker image? [yes/NO]: ",
135
+ _convert_yes_no_to_bool,
136
+ default=False,
137
+ error_message="Please enter yes or no.",
138
+ )
139
+ docker_image = None
140
+ if is_custom_docker_image:
141
+ docker_image = _ask_field("Enter your Docker image: ", lambda x: str(x).lower())
142
+
143
+ is_sagemaker_inputs_enabled = _ask_field(
144
+ "Do you want to provide SageMaker input channels with data locations? [yes/NO]: ",
145
+ _convert_yes_no_to_bool,
146
+ default=False,
147
+ error_message="Please enter yes or no.",
148
+ )
149
+ sagemaker_inputs_file = None
150
+ if is_sagemaker_inputs_enabled:
151
+ sagemaker_inputs_file = _ask_field(
152
+ "Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): ",
153
+ lambda x: str(x).lower(),
154
+ )
155
+
156
+ is_sagemaker_metrics_enabled = _ask_field(
157
+ "Do you want to enable SageMaker metrics? [yes/NO]: ",
158
+ _convert_yes_no_to_bool,
159
+ default=False,
160
+ error_message="Please enter yes or no.",
161
+ )
162
+ sagemaker_metrics_file = None
163
+ if is_sagemaker_metrics_enabled:
164
+ sagemaker_metrics_file = _ask_field(
165
+ "Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): ",
166
+ lambda x: str(x).lower(),
167
+ )
168
+
169
+ distributed_type = _ask_options(
170
+ "What is the distributed mode?",
171
+ ["No distributed training", "Data parallelism"],
172
+ _convert_sagemaker_distributed_mode,
173
+ )
174
+ dynamo_config = {}
175
+ use_dynamo = _ask_field(
176
+ "Do you wish to optimize your script with torch dynamo?[yes/NO]:",
177
+ _convert_yes_no_to_bool,
178
+ default=False,
179
+ error_message="Please enter yes or no.",
180
+ )
181
+ if use_dynamo:
182
+ prefix = "dynamo_"
183
+ dynamo_config[prefix + "backend"] = _ask_options(
184
+ "Which dynamo backend would you like to use?",
185
+ [x.lower() for x in DYNAMO_BACKENDS],
186
+ _convert_dynamo_backend,
187
+ default=2,
188
+ )
189
+ use_custom_options = _ask_field(
190
+ "Do you want to customize the defaults sent to torch.compile? [yes/NO]: ",
191
+ _convert_yes_no_to_bool,
192
+ default=False,
193
+ error_message="Please enter yes or no.",
194
+ )
195
+
196
+ if use_custom_options:
197
+ dynamo_config[prefix + "mode"] = _ask_options(
198
+ "Which mode do you want to use?",
199
+ TORCH_DYNAMO_MODES,
200
+ lambda x: TORCH_DYNAMO_MODES[int(x)],
201
+ default="default",
202
+ )
203
+ dynamo_config[prefix + "use_fullgraph"] = _ask_field(
204
+ "Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: ",
205
+ _convert_yes_no_to_bool,
206
+ default=False,
207
+ error_message="Please enter yes or no.",
208
+ )
209
+ dynamo_config[prefix + "use_dynamic"] = _ask_field(
210
+ "Do you want to enable dynamic shape tracing? [yes/NO]: ",
211
+ _convert_yes_no_to_bool,
212
+ default=False,
213
+ error_message="Please enter yes or no.",
214
+ )
215
+ dynamo_config[prefix + "use_regional_compilation"] = _ask_field(
216
+ "Do you want to enable regional compilation? [yes/NO]: ",
217
+ _convert_yes_no_to_bool,
218
+ default=False,
219
+ error_message="Please enter yes or no.",
220
+ )
221
+
222
+ ec2_instance_query = "Which EC2 instance type you want to use for your training?"
223
+ if distributed_type != SageMakerDistributedType.NO:
224
+ ec2_instance_type = _ask_options(
225
+ ec2_instance_query, SAGEMAKER_PARALLEL_EC2_INSTANCES, lambda x: SAGEMAKER_PARALLEL_EC2_INSTANCES[int(x)]
226
+ )
227
+ else:
228
+ ec2_instance_query += "? [ml.p3.2xlarge]:"
229
+ ec2_instance_type = _ask_field(ec2_instance_query, lambda x: str(x).lower(), default="ml.p3.2xlarge")
230
+
231
+ debug = False
232
+ if distributed_type != SageMakerDistributedType.NO:
233
+ debug = _ask_field(
234
+ "Should distributed operations be checked while running for errors? This can avoid timeout issues but will be slower. [yes/NO]: ",
235
+ _convert_yes_no_to_bool,
236
+ default=False,
237
+ error_message="Please enter yes or no.",
238
+ )
239
+
240
+ num_machines = 1
241
+ if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL):
242
+ num_machines = _ask_field(
243
+ "How many machines do you want use? [1]: ",
244
+ int,
245
+ default=1,
246
+ )
247
+
248
+ mixed_precision = _ask_options(
249
+ "Do you wish to use FP16 or BF16 (mixed precision)?",
250
+ ["no", "fp16", "bf16", "fp8"],
251
+ _convert_mixed_precision,
252
+ )
253
+
254
+ if use_dynamo and mixed_precision == "no":
255
+ print(
256
+ "Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts."
257
+ )
258
+
259
+ return SageMakerConfig(
260
+ image_uri=docker_image,
261
+ compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER,
262
+ distributed_type=distributed_type,
263
+ use_cpu=False,
264
+ dynamo_config=dynamo_config,
265
+ ec2_instance_type=ec2_instance_type,
266
+ profile=aws_profile,
267
+ region=aws_region,
268
+ iam_role_name=iam_role_name,
269
+ mixed_precision=mixed_precision,
270
+ num_machines=num_machines,
271
+ sagemaker_inputs_file=sagemaker_inputs_file,
272
+ sagemaker_metrics_file=sagemaker_metrics_file,
273
+ debug=debug,
274
+ )
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/config/update.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ from pathlib import Path
18
+
19
+ from .config_args import default_config_file, load_config_from_file
20
+ from .config_utils import SubcommandHelpFormatter
21
+
22
+
23
+ description = "Update an existing config file with the latest defaults while maintaining the old configuration."
24
+
25
+
26
+ def update_config(args):
27
+ """
28
+ Update an existing config file with the latest defaults while maintaining the old configuration.
29
+ """
30
+ config_file = args.config_file
31
+ if config_file is None and Path(default_config_file).exists():
32
+ config_file = default_config_file
33
+ elif not Path(config_file).exists():
34
+ raise ValueError(f"The passed config file located at {config_file} doesn't exist.")
35
+ config = load_config_from_file(config_file)
36
+
37
+ if config_file.endswith(".json"):
38
+ config.to_json_file(config_file)
39
+ else:
40
+ config.to_yaml_file(config_file)
41
+ return config_file
42
+
43
+
44
+ def update_command_parser(parser, parents):
45
+ parser = parser.add_parser("update", parents=parents, help=description, formatter_class=SubcommandHelpFormatter)
46
+ parser.add_argument(
47
+ "--config_file",
48
+ default=None,
49
+ help=(
50
+ "The path to the config file to update. Will default to a file named default_config.yaml in the cache "
51
+ "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have "
52
+ "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed "
53
+ "with 'huggingface'."
54
+ ),
55
+ )
56
+
57
+ parser.set_defaults(func=update_config_command)
58
+ return parser
59
+
60
+
61
+ def update_config_command(args):
62
+ config_file = update_config(args)
63
+ print(f"Sucessfully updated the configuration file at {config_file}.")
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/env.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import argparse
18
+ import os
19
+ import platform
20
+ import subprocess
21
+
22
+ import numpy as np
23
+ import psutil
24
+ import torch
25
+
26
+ from accelerate import __version__ as version
27
+ from accelerate.commands.config import default_config_file, load_config_from_file
28
+
29
+ from ..utils import is_mlu_available, is_musa_available, is_npu_available, is_sdaa_available, is_xpu_available
30
+
31
+
32
+ def env_command_parser(subparsers=None):
33
+ if subparsers is not None:
34
+ parser = subparsers.add_parser("env")
35
+ else:
36
+ parser = argparse.ArgumentParser("Accelerate env command")
37
+
38
+ parser.add_argument(
39
+ "--config_file", default=None, help="The config file to use for the default values in the launching script."
40
+ )
41
+
42
+ if subparsers is not None:
43
+ parser.set_defaults(func=env_command)
44
+ return parser
45
+
46
+
47
+ def env_command(args):
48
+ pt_version = torch.__version__
49
+ pt_cuda_available = torch.cuda.is_available()
50
+ pt_xpu_available = is_xpu_available()
51
+ pt_mlu_available = is_mlu_available()
52
+ pt_sdaa_available = is_sdaa_available()
53
+ pt_musa_available = is_musa_available()
54
+ pt_npu_available = is_npu_available()
55
+
56
+ accelerator = "N/A"
57
+ if pt_cuda_available:
58
+ accelerator = "CUDA"
59
+ elif pt_xpu_available:
60
+ accelerator = "XPU"
61
+ elif pt_mlu_available:
62
+ accelerator = "MLU"
63
+ elif pt_sdaa_available:
64
+ accelerator = "SDAA"
65
+ elif pt_musa_available:
66
+ accelerator = "MUSA"
67
+ elif pt_npu_available:
68
+ accelerator = "NPU"
69
+
70
+ accelerate_config = "Not found"
71
+ # Get the default from the config file.
72
+ if args.config_file is not None or os.path.isfile(default_config_file):
73
+ accelerate_config = load_config_from_file(args.config_file).to_dict()
74
+
75
+ # if we can run which, get it
76
+ command = None
77
+ bash_location = "Not found"
78
+ if os.name == "nt":
79
+ command = ["where", "accelerate"]
80
+ elif os.name == "posix":
81
+ command = ["which", "accelerate"]
82
+ if command is not None:
83
+ bash_location = subprocess.check_output(command, text=True, stderr=subprocess.STDOUT).strip()
84
+ info = {
85
+ "`Accelerate` version": version,
86
+ "Platform": platform.platform(),
87
+ "`accelerate` bash location": bash_location,
88
+ "Python version": platform.python_version(),
89
+ "Numpy version": np.__version__,
90
+ "PyTorch version": f"{pt_version}",
91
+ "PyTorch accelerator": accelerator,
92
+ "System RAM": f"{psutil.virtual_memory().total / 1024**3:.2f} GB",
93
+ }
94
+ if pt_cuda_available:
95
+ info["GPU type"] = torch.cuda.get_device_name()
96
+ elif pt_xpu_available:
97
+ info["XPU type"] = torch.xpu.get_device_name()
98
+ elif pt_mlu_available:
99
+ info["MLU type"] = torch.mlu.get_device_name()
100
+ elif pt_sdaa_available:
101
+ info["SDAA type"] = torch.sdaa.get_device_name()
102
+ elif pt_musa_available:
103
+ info["MUSA type"] = torch.musa.get_device_name()
104
+ elif pt_npu_available:
105
+ info["CANN version"] = torch.version.cann
106
+
107
+ print("\nCopy-and-paste the text below in your GitHub issue\n")
108
+ print("\n".join([f"- {prop}: {val}" for prop, val in info.items()]))
109
+
110
+ print("- `Accelerate` default config:" if args.config_file is None else "- `Accelerate` config passed:")
111
+ accelerate_config_str = (
112
+ "\n".join([f"\t- {prop}: {val}" for prop, val in accelerate_config.items()])
113
+ if isinstance(accelerate_config, dict)
114
+ else f"\t{accelerate_config}"
115
+ )
116
+ print(accelerate_config_str)
117
+
118
+ info["`Accelerate` configs"] = accelerate_config
119
+
120
+ return info
121
+
122
+
123
+ def main() -> int:
124
+ parser = env_command_parser()
125
+ args = parser.parse_args()
126
+ env_command(args)
127
+ return 0
128
+
129
+
130
+ if __name__ == "__main__":
131
+ raise SystemExit(main())
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/estimate.py ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ import torch
17
+ from huggingface_hub import model_info
18
+ from huggingface_hub.utils import GatedRepoError, RepositoryNotFoundError
19
+
20
+ from accelerate import init_empty_weights
21
+ from accelerate.commands.utils import CustomArgumentParser
22
+ from accelerate.utils import (
23
+ calculate_maximum_sizes,
24
+ convert_bytes,
25
+ is_timm_available,
26
+ is_transformers_available,
27
+ )
28
+
29
+
30
+ if is_transformers_available():
31
+ import transformers
32
+ from transformers import AutoConfig, AutoModel
33
+
34
+ if is_timm_available():
35
+ import timm
36
+
37
+
38
+ def verify_on_hub(repo: str, token: str = None):
39
+ "Verifies that the model is on the hub and returns the model info."
40
+ try:
41
+ return model_info(repo, token=token)
42
+ except (OSError, GatedRepoError):
43
+ return "gated"
44
+ except RepositoryNotFoundError:
45
+ return "repo"
46
+
47
+
48
+ def check_has_model(error):
49
+ """
50
+ Checks what library spawned `error` when a model is not found
51
+ """
52
+ if is_timm_available() and isinstance(error, RuntimeError) and "Unknown model" in error.args[0]:
53
+ return "timm"
54
+ elif (
55
+ is_transformers_available()
56
+ and isinstance(error, OSError)
57
+ and "does not appear to have a file named" in error.args[0]
58
+ ):
59
+ return "transformers"
60
+ else:
61
+ return "unknown"
62
+
63
+
64
+ def create_empty_model(model_name: str, library_name: str, trust_remote_code: bool = False, access_token: str = None):
65
+ """
66
+ Creates an empty model in full precision from its parent library on the `Hub` to calculate the overall memory
67
+ consumption.
68
+
69
+ Args:
70
+ model_name (`str`):
71
+ The model name on the Hub
72
+ library_name (`str`):
73
+ The library the model has an integration with, such as `transformers`. Will be used if `model_name` has no
74
+ metadata on the Hub to determine the library.
75
+ trust_remote_code (`bool`, `optional`, defaults to `False`):
76
+ Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
77
+ should only be set to `True` for repositories you trust and in which you have read the code, as it will
78
+ execute code present on the Hub on your local machine.
79
+ access_token (`str`, `optional`, defaults to `None`):
80
+ The access token to use to access private or gated models on the Hub. (for use on the Gradio app)
81
+
82
+ Returns:
83
+ `torch.nn.Module`: The torch model that has been initialized on the `meta` device.
84
+
85
+ """
86
+ model_info = verify_on_hub(model_name, access_token)
87
+ # Simplified errors
88
+ if model_info == "gated":
89
+ raise GatedRepoError(
90
+ f"Repo for model `{model_name}` is gated. You must be authenticated to access it. Please run `huggingface-cli login`."
91
+ )
92
+ elif model_info == "repo":
93
+ raise RepositoryNotFoundError(
94
+ f"Repo for model `{model_name}` does not exist on the Hub. If you are trying to access a private repo,"
95
+ " make sure you are authenticated via `huggingface-cli login` and have access."
96
+ )
97
+ if library_name is None:
98
+ library_name = getattr(model_info, "library_name", False)
99
+ if not library_name:
100
+ raise ValueError(
101
+ 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`)"
102
+ )
103
+ if library_name == "transformers":
104
+ if not is_transformers_available():
105
+ raise ImportError(
106
+ f"To check `{model_name}`, `transformers` must be installed. Please install it via `pip install transformers`"
107
+ )
108
+ print(f"Loading pretrained config for `{model_name}` from `transformers`...")
109
+ if model_info.config is None:
110
+ raise RuntimeError(f"Tried to load `{model_name}` with `transformers` but it does not have any metadata.")
111
+
112
+ auto_map = model_info.config.get("auto_map", False)
113
+ config = AutoConfig.from_pretrained(model_name, trust_remote_code=trust_remote_code, token=access_token)
114
+ with init_empty_weights():
115
+ # remote code could specify a specific `AutoModel` class in the `auto_map`
116
+ constructor = AutoModel
117
+ if isinstance(auto_map, dict):
118
+ value = None
119
+ for key in auto_map.keys():
120
+ if key.startswith("AutoModelFor"):
121
+ value = key
122
+ break
123
+ if value is not None:
124
+ constructor = getattr(transformers, value)
125
+ # we need to pass the dtype, otherwise it is going to use the torch_dtype that is saved in the config
126
+ model = constructor.from_config(config, torch_dtype=torch.float32, trust_remote_code=trust_remote_code)
127
+ elif library_name == "timm":
128
+ if not is_timm_available():
129
+ raise ImportError(
130
+ f"To check `{model_name}`, `timm` must be installed. Please install it via `pip install timm`"
131
+ )
132
+ print(f"Loading pretrained config for `{model_name}` from `timm`...")
133
+ with init_empty_weights():
134
+ model = timm.create_model(model_name, pretrained=False)
135
+ else:
136
+ raise ValueError(
137
+ f"Library `{library_name}` is not supported yet, please open an issue on GitHub for us to add support."
138
+ )
139
+ return model
140
+
141
+
142
+ def create_ascii_table(headers: list, rows: list, title: str):
143
+ "Creates a pretty table from a list of rows, minimal version of `tabulate`."
144
+ sep_char, in_between = "│", "─"
145
+ column_widths = []
146
+ for i in range(len(headers)):
147
+ column_values = [row[i] for row in rows] + [headers[i]]
148
+ max_column_width = max(len(value) for value in column_values)
149
+ column_widths.append(max_column_width)
150
+
151
+ formats = [f"%{column_widths[i]}s" for i in range(len(rows[0]))]
152
+
153
+ pattern = f"{sep_char}{sep_char.join(formats)}{sep_char}"
154
+ diff = 0
155
+
156
+ def make_row(left_char, middle_char, right_char):
157
+ return f"{left_char}{middle_char.join([in_between * n for n in column_widths])}{in_between * diff}{right_char}"
158
+
159
+ separator = make_row("├", "┼", "┤")
160
+ if len(title) > sum(column_widths):
161
+ diff = abs(len(title) - len(separator))
162
+ column_widths[-1] += diff
163
+
164
+ # Update with diff
165
+ separator = make_row("├", "┼", "┤")
166
+ initial_rows = [
167
+ make_row("┌", in_between, "┐"),
168
+ f"{sep_char}{title.center(len(separator) - 2)}{sep_char}",
169
+ make_row("├", "┬", "┤"),
170
+ ]
171
+ table = "\n".join(initial_rows) + "\n"
172
+ column_widths[-1] += diff
173
+ centered_line = [text.center(column_widths[i]) for i, text in enumerate(headers)]
174
+ table += f"{pattern % tuple(centered_line)}\n{separator}\n"
175
+ for i, line in enumerate(rows):
176
+ centered_line = [t.center(column_widths[i]) for i, t in enumerate(line)]
177
+ table += f"{pattern % tuple(centered_line)}\n"
178
+ table += f"└{'┴'.join([in_between * n for n in column_widths])}┘"
179
+
180
+ return table
181
+
182
+
183
+ def estimate_command_parser(subparsers=None):
184
+ if subparsers is not None:
185
+ parser = subparsers.add_parser("estimate-memory")
186
+ else:
187
+ parser = CustomArgumentParser(description="Model size estimator for fitting a model onto CUDA memory.")
188
+
189
+ parser.add_argument("model_name", type=str, help="The model name on the Hugging Face Hub.")
190
+ parser.add_argument(
191
+ "--library_name",
192
+ type=str,
193
+ help="The library the model has an integration with, such as `transformers`, needed only if this information is not stored on the Hub.",
194
+ choices=["timm", "transformers"],
195
+ )
196
+ parser.add_argument(
197
+ "--dtypes",
198
+ type=str,
199
+ nargs="+",
200
+ default=["float32", "float16", "int8", "int4"],
201
+ help="The dtypes to use for the model, must be one (or many) of `float32`, `float16`, `int8`, and `int4`",
202
+ choices=["float32", "float16", "int8", "int4"],
203
+ )
204
+ parser.add_argument(
205
+ "--trust_remote_code",
206
+ action="store_true",
207
+ help="""Whether or not to allow for custom models defined on the Hub in their own modeling files. This flag
208
+ should only be used for repositories you trust and in which you have read the code, as it will execute
209
+ code present on the Hub on your local machine.""",
210
+ default=False,
211
+ )
212
+
213
+ if subparsers is not None:
214
+ parser.set_defaults(func=estimate_command)
215
+ return parser
216
+
217
+
218
+ def estimate_training_usage(bytes: int, mixed_precision: str, msamp_config: str = None) -> dict:
219
+ """
220
+ Given an amount of `bytes` and `mixed_precision`, calculates how much training memory is needed for a batch size of
221
+ 1.
222
+
223
+ Args:
224
+ bytes (`int`):
225
+ The size of the model being trained.
226
+ mixed_precision (`str`):
227
+ The mixed precision that would be ran.
228
+ msamp_config (`str`):
229
+ The msamp config to estimate the training memory for if `mixed_precision` is set to `"fp8"`.
230
+ """
231
+ memory_sizes = {"model": -1, "optimizer": -1, "gradients": -1, "step": -1}
232
+ fp32_size = bytes
233
+ fp16_size = bytes // 2
234
+
235
+ if mixed_precision == "float32":
236
+ memory_sizes["model"] = fp32_size
237
+ memory_sizes["gradients"] = fp32_size
238
+ memory_sizes["optimizer"] = fp32_size * 2
239
+ memory_sizes["step"] = fp32_size * 4
240
+ elif mixed_precision in ("float16", "bfloat16") or (mixed_precision == "fp8" and msamp_config is None):
241
+ # With native `TransformersEngine`, there is no memory savings with FP8
242
+ # With mixed precision training, the model has weights stored
243
+ # in FP16 and FP32
244
+ memory_sizes["model"] = fp32_size
245
+ # 1.5 from weight gradient + computation (GEMM)
246
+ memory_sizes["gradients"] = fp32_size + fp16_size
247
+ # 2x from optimizer states
248
+ memory_sizes["optimizer"] = fp32_size * 2 # Optimizer states
249
+ memory_sizes["step"] = memory_sizes["optimizer"]
250
+ return memory_sizes
251
+
252
+
253
+ def gather_data(args):
254
+ "Creates an empty model and gathers the data for the sizes"
255
+ try:
256
+ model = create_empty_model(
257
+ args.model_name, library_name=args.library_name, trust_remote_code=args.trust_remote_code
258
+ )
259
+ except (RuntimeError, OSError) as e:
260
+ library = check_has_model(e)
261
+ if library != "unknown":
262
+ raise RuntimeError(
263
+ f"Tried to load `{args.model_name}` with `{library}` but a possible model to load was not found inside the repo."
264
+ )
265
+ raise e
266
+
267
+ total_size, largest_layer = calculate_maximum_sizes(model)
268
+
269
+ data = []
270
+
271
+ for dtype in args.dtypes:
272
+ dtype_total_size = total_size
273
+ dtype_largest_layer = largest_layer[0]
274
+ dtype_training_size = estimate_training_usage(dtype_total_size, dtype)
275
+ if dtype == "float16":
276
+ dtype_total_size /= 2
277
+ dtype_largest_layer /= 2
278
+ elif dtype == "int8":
279
+ dtype_total_size /= 4
280
+ dtype_largest_layer /= 4
281
+ elif dtype == "int4":
282
+ dtype_total_size /= 8
283
+ dtype_largest_layer /= 8
284
+ data.append([dtype, dtype_largest_layer, dtype_total_size, dtype_training_size])
285
+ return data
286
+
287
+
288
+ def estimate_command(args):
289
+ data = gather_data(args)
290
+ for row in data:
291
+ for i, item in enumerate(row):
292
+ if isinstance(item, (int, float)):
293
+ row[i] = convert_bytes(item)
294
+ elif isinstance(item, dict):
295
+ training_usage = max(item.values())
296
+ row[i] = convert_bytes(training_usage) if training_usage != -1 else "N/A"
297
+
298
+ headers = ["dtype", "Largest Layer", "Total Size", "Training using Adam"]
299
+
300
+ title = f"Memory Usage for loading `{args.model_name}`"
301
+ table = create_ascii_table(headers, data, title)
302
+ print(table)
303
+
304
+
305
+ def main():
306
+ parser = estimate_command_parser()
307
+ args = parser.parse_args()
308
+ estimate_command(args)
309
+
310
+
311
+ if __name__ == "__main__":
312
+ main()
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/launch.py ADDED
@@ -0,0 +1,1258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2021 The HuggingFace Team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import argparse
18
+ import importlib
19
+ import logging
20
+ import os
21
+ import subprocess
22
+ import sys
23
+ from pathlib import Path
24
+
25
+ import psutil
26
+ import torch
27
+
28
+ from accelerate.commands.config import default_config_file, load_config_from_file
29
+ from accelerate.commands.config.config_args import SageMakerConfig
30
+ from accelerate.commands.config.config_utils import DYNAMO_BACKENDS
31
+ from accelerate.commands.utils import CustomArgumentParser
32
+ from accelerate.state import get_int_from_env
33
+ from accelerate.utils import (
34
+ ComputeEnvironment,
35
+ DistributedType,
36
+ PrepareForLaunch,
37
+ _filter_args,
38
+ check_cuda_p2p_ib_support,
39
+ convert_dict_to_env_variables,
40
+ is_bf16_available,
41
+ is_deepspeed_available,
42
+ is_hpu_available,
43
+ is_mlu_available,
44
+ is_musa_available,
45
+ is_npu_available,
46
+ is_rich_available,
47
+ is_sagemaker_available,
48
+ is_sdaa_available,
49
+ is_torch_xla_available,
50
+ is_xpu_available,
51
+ patch_environment,
52
+ prepare_deepspeed_cmd_env,
53
+ prepare_multi_gpu_env,
54
+ prepare_sagemager_args_inputs,
55
+ prepare_simple_launcher_cmd_env,
56
+ prepare_tpu,
57
+ str_to_bool,
58
+ )
59
+ from accelerate.utils.constants import DEEPSPEED_MULTINODE_LAUNCHERS, TORCH_DYNAMO_MODES
60
+
61
+
62
+ if is_rich_available():
63
+ from rich import get_console
64
+ from rich.logging import RichHandler
65
+
66
+ FORMAT = "%(message)s"
67
+ logging.basicConfig(format=FORMAT, datefmt="[%X]", handlers=[RichHandler()])
68
+
69
+
70
+ logger = logging.getLogger(__name__)
71
+
72
+
73
+ options_to_group = {
74
+ "multi_gpu": "Distributed GPUs",
75
+ "tpu": "TPU",
76
+ "use_deepspeed": "DeepSpeed Arguments",
77
+ "use_fsdp": "FSDP Arguments",
78
+ "use_megatron_lm": "Megatron-LM Arguments",
79
+ "fp8_backend": "FP8 Arguments",
80
+ }
81
+
82
+
83
+ def clean_option(option):
84
+ "Finds all cases of - after the first two characters and changes them to _"
85
+ if "fp8_backend" in option:
86
+ option = "--fp8_backend"
87
+ if option.startswith("--"):
88
+ return option[2:].replace("-", "_")
89
+
90
+
91
+ class CustomHelpFormatter(argparse.HelpFormatter):
92
+ """
93
+ This is a custom help formatter that will hide all arguments that are not used in the command line when the help is
94
+ called. This is useful for the case where the user is using a specific platform and only wants to see the arguments
95
+ for that platform.
96
+ """
97
+
98
+ def __init__(self, *args, **kwargs):
99
+ super().__init__(*args, **kwargs)
100
+ self.titles = [
101
+ "Hardware Selection Arguments",
102
+ "Resource Selection Arguments",
103
+ "Training Paradigm Arguments",
104
+ "positional arguments",
105
+ "optional arguments",
106
+ ]
107
+
108
+ def add_argument(self, action: argparse.Action):
109
+ if "accelerate" in sys.argv[0] and "launch" in sys.argv[1:]:
110
+ args = sys.argv[2:]
111
+ else:
112
+ args = sys.argv[1:]
113
+
114
+ if len(args) > 1:
115
+ args = list(map(clean_option, args))
116
+ used_platforms = [arg for arg in args if arg in options_to_group.keys()]
117
+ used_titles = [options_to_group[o] for o in used_platforms]
118
+ if action.container.title not in self.titles + used_titles:
119
+ action.help = argparse.SUPPRESS
120
+ elif action.container.title == "Hardware Selection Arguments":
121
+ if set(action.option_strings).isdisjoint(set(args)):
122
+ action.help = argparse.SUPPRESS
123
+ else:
124
+ action.help = action.help + " (currently selected)"
125
+ elif action.container.title == "Training Paradigm Arguments":
126
+ if set(action.option_strings).isdisjoint(set(args)):
127
+ action.help = argparse.SUPPRESS
128
+ else:
129
+ action.help = action.help + " (currently selected)"
130
+
131
+ action.option_strings = [s for s in action.option_strings if "-" not in s[2:]]
132
+ super().add_argument(action)
133
+
134
+ def end_section(self):
135
+ if len(self._current_section.items) < 2:
136
+ self._current_section.items = []
137
+ self._current_section.heading = ""
138
+ super().end_section()
139
+
140
+
141
+ def launch_command_parser(subparsers=None):
142
+ 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`)"
143
+ if subparsers is not None:
144
+ parser = subparsers.add_parser(
145
+ "launch", description=description, add_help=False, allow_abbrev=False, formatter_class=CustomHelpFormatter
146
+ )
147
+ else:
148
+ parser = CustomArgumentParser(
149
+ "Accelerate launch command",
150
+ description=description,
151
+ add_help=False,
152
+ allow_abbrev=False,
153
+ formatter_class=CustomHelpFormatter,
154
+ )
155
+
156
+ parser.add_argument("-h", "--help", action="help", help="Show this help message and exit.")
157
+
158
+ parser.add_argument(
159
+ "--config_file",
160
+ default=None,
161
+ help="The config file to use for the default values in the launching script.",
162
+ )
163
+ parser.add_argument(
164
+ "--quiet",
165
+ "-q",
166
+ action="store_true",
167
+ help="Silence subprocess errors from the launch stack trace and only show the relevant tracebacks. (Only applicable to DeepSpeed and single-process configurations)",
168
+ )
169
+ # Hardware selection arguments
170
+ hardware_args = parser.add_argument_group(
171
+ "Hardware Selection Arguments", "Arguments for selecting the hardware to be used."
172
+ )
173
+ hardware_args.add_argument(
174
+ "--cpu", default=False, action="store_true", help="Whether or not to force the training on the CPU."
175
+ )
176
+ hardware_args.add_argument(
177
+ "--multi_gpu",
178
+ default=False,
179
+ action="store_true",
180
+ help="Whether or not this should launch a distributed GPU training.",
181
+ )
182
+ hardware_args.add_argument(
183
+ "--tpu", default=False, action="store_true", help="Whether or not this should launch a TPU training."
184
+ )
185
+ hardware_args.add_argument(
186
+ "--ipex",
187
+ default=False,
188
+ action="store_true",
189
+ help="Whether or not this should launch a Intel PyTorch Extension (IPEX) training.",
190
+ )
191
+
192
+ # Resource selection arguments
193
+ resource_args = parser.add_argument_group(
194
+ "Resource Selection Arguments", "Arguments for fine-tuning how available hardware should be used."
195
+ )
196
+ resource_args.add_argument(
197
+ "--mixed_precision",
198
+ type=str,
199
+ choices=["no", "fp16", "bf16", "fp8"],
200
+ help="Whether or not to use mixed precision training. "
201
+ "Choose between FP16 and BF16 (bfloat16) training. "
202
+ "BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.",
203
+ )
204
+ resource_args.add_argument(
205
+ "--num_processes", type=int, default=None, help="The total number of processes to be launched in parallel."
206
+ )
207
+ resource_args.add_argument(
208
+ "--num_machines", type=int, default=None, help="The total number of machines used in this training."
209
+ )
210
+ resource_args.add_argument(
211
+ "--num_cpu_threads_per_process",
212
+ type=int,
213
+ default=None,
214
+ help="The number of CPU threads per process. Can be tuned for optimal performance.",
215
+ )
216
+ resource_args.add_argument(
217
+ "--enable_cpu_affinity",
218
+ default=False,
219
+ action="store_true",
220
+ help="Whether or not CPU affinity and balancing should be enabled. Currently only supported on NVIDIA hardware.",
221
+ )
222
+ # Dynamo arguments
223
+ resource_args.add_argument(
224
+ "--dynamo_backend",
225
+ type=str,
226
+ choices=["no"] + [b.lower() for b in DYNAMO_BACKENDS],
227
+ help="Choose a backend to optimize your training with dynamo, see more at "
228
+ "https://github.com/pytorch/torchdynamo.",
229
+ )
230
+ resource_args.add_argument(
231
+ "--dynamo_mode",
232
+ type=str,
233
+ default="default",
234
+ choices=TORCH_DYNAMO_MODES,
235
+ help="Choose a mode to optimize your training with dynamo.",
236
+ )
237
+ resource_args.add_argument(
238
+ "--dynamo_use_fullgraph",
239
+ default=False,
240
+ action="store_true",
241
+ help="Whether to use full graph mode for dynamo or it is ok to break model into several subgraphs",
242
+ )
243
+ resource_args.add_argument(
244
+ "--dynamo_use_dynamic",
245
+ default=False,
246
+ action="store_true",
247
+ help="Whether to enable dynamic shape tracing.",
248
+ )
249
+ resource_args.add_argument(
250
+ "--dynamo_use_regional_compilation",
251
+ default=False,
252
+ action="store_true",
253
+ help="Whether to enable regional compilation.",
254
+ )
255
+
256
+ # Training Paradigm arguments
257
+ paradigm_args = parser.add_argument_group(
258
+ "Training Paradigm Arguments", "Arguments for selecting which training paradigm to be used."
259
+ )
260
+ paradigm_args.add_argument(
261
+ "--use_deepspeed",
262
+ default=False,
263
+ action="store_true",
264
+ help="Whether to use deepspeed.",
265
+ )
266
+ paradigm_args.add_argument(
267
+ "--use_fsdp",
268
+ default=False,
269
+ action="store_true",
270
+ help="Whether to use fsdp.",
271
+ )
272
+ paradigm_args.add_argument(
273
+ "--use_parallelism_config",
274
+ default=False,
275
+ action="store_true",
276
+ help="Whether to use the parallelism config to configure the N-d distributed training.",
277
+ )
278
+ paradigm_args.add_argument(
279
+ "--use_megatron_lm",
280
+ default=False,
281
+ action="store_true",
282
+ help="Whether to use Megatron-LM.",
283
+ )
284
+
285
+ paradigm_args.add_argument(
286
+ "--use_xpu",
287
+ default=None,
288
+ action="store_true",
289
+ 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.",
290
+ )
291
+
292
+ # distributed GPU training arguments
293
+ distributed_args = parser.add_argument_group("Distributed GPUs", "Arguments related to distributed GPU training.")
294
+ distributed_args.add_argument(
295
+ "--gpu_ids",
296
+ default=None,
297
+ help="What GPUs (by id) should be used for training on this machine as a comma-separated list",
298
+ )
299
+ distributed_args.add_argument(
300
+ "--same_network",
301
+ default=False,
302
+ action="store_true",
303
+ help="Whether all machines used for multinode training exist on the same local network.",
304
+ )
305
+ distributed_args.add_argument(
306
+ "--machine_rank", type=int, default=None, help="The rank of the machine on which this script is launched."
307
+ )
308
+ distributed_args.add_argument(
309
+ "--main_process_ip", type=str, default=None, help="The IP address of the machine of rank 0."
310
+ )
311
+ distributed_args.add_argument(
312
+ "--main_process_port",
313
+ type=int,
314
+ default=None,
315
+ help="The port to use to communicate with the machine of rank 0.",
316
+ )
317
+ distributed_args.add_argument(
318
+ "-t",
319
+ "--tee",
320
+ default="0",
321
+ type=str,
322
+ help="Tee std streams into a log file and also to console.",
323
+ )
324
+ distributed_args.add_argument(
325
+ "--log_dir",
326
+ type=str,
327
+ default=None,
328
+ help=(
329
+ "Base directory to use for log files when using torchrun/torch.distributed.run as launcher. "
330
+ "Use with --tee to redirect std streams info log files."
331
+ ),
332
+ )
333
+ distributed_args.add_argument(
334
+ "--role",
335
+ type=str,
336
+ default="default",
337
+ help="User-defined role for the workers.",
338
+ )
339
+ # Rendezvous related arguments
340
+ distributed_args.add_argument(
341
+ "--rdzv_backend",
342
+ type=str,
343
+ default="static",
344
+ help="The rendezvous method to use, such as 'static' (the default) or 'c10d'",
345
+ )
346
+ distributed_args.add_argument(
347
+ "--rdzv_conf",
348
+ type=str,
349
+ default="",
350
+ help="Additional rendezvous configuration (<key1>=<value1>,<key2>=<value2>,...).",
351
+ )
352
+ distributed_args.add_argument(
353
+ "--max_restarts",
354
+ type=int,
355
+ default=0,
356
+ help="Maximum number of worker group restarts before failing.",
357
+ )
358
+ distributed_args.add_argument(
359
+ "--monitor_interval",
360
+ type=float,
361
+ default=0.1,
362
+ help="Interval, in seconds, to monitor the state of workers.",
363
+ )
364
+ parser.add_argument(
365
+ "-m",
366
+ "--module",
367
+ action="store_true",
368
+ help="Change each process to interpret the launch script as a Python module, executing with the same behavior as 'python -m'.",
369
+ )
370
+ parser.add_argument(
371
+ "--no_python",
372
+ action="store_true",
373
+ help="Skip prepending the training script with 'python' - just execute it directly. Useful when the script is not a Python script.",
374
+ )
375
+
376
+ # TPU arguments
377
+ tpu_args = parser.add_argument_group("TPU", "Arguments related to TPU.")
378
+ tpu_args.add_argument(
379
+ "--tpu_cluster",
380
+ action="store_true",
381
+ dest="tpu_use_cluster",
382
+ help="Whether to use a GCP TPU pod for training.",
383
+ )
384
+ tpu_args.add_argument(
385
+ "--no_tpu_cluster",
386
+ action="store_false",
387
+ dest="tpu_use_cluster",
388
+ help="Should not be passed explicitly, this is for internal use only.",
389
+ )
390
+ tpu_args.add_argument(
391
+ "--tpu_use_sudo",
392
+ action="store_true",
393
+ help="Whether to use `sudo` when running the TPU training script in each pod.",
394
+ )
395
+ tpu_args.add_argument(
396
+ "--vm",
397
+ type=str,
398
+ action="append",
399
+ help=(
400
+ "List of single Compute VM instance names. "
401
+ "If not provided we assume usage of instance groups. For TPU pods."
402
+ ),
403
+ )
404
+ tpu_args.add_argument(
405
+ "--env",
406
+ type=str,
407
+ action="append",
408
+ help="List of environment variables to set on the Compute VM instances. For TPU pods.",
409
+ )
410
+ tpu_args.add_argument(
411
+ "--main_training_function",
412
+ type=str,
413
+ default=None,
414
+ help="The name of the main function to be executed in your script (only for TPU training).",
415
+ )
416
+ tpu_args.add_argument(
417
+ "--downcast_bf16",
418
+ action="store_true",
419
+ 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.",
420
+ )
421
+
422
+ # DeepSpeed arguments
423
+ deepspeed_args = parser.add_argument_group("DeepSpeed Arguments", "Arguments related to DeepSpeed.")
424
+ deepspeed_args.add_argument(
425
+ "--deepspeed_config_file",
426
+ default=None,
427
+ type=str,
428
+ help="DeepSpeed config file.",
429
+ )
430
+ deepspeed_args.add_argument(
431
+ "--zero_stage",
432
+ default=None,
433
+ type=int,
434
+ help="DeepSpeed's ZeRO optimization stage (useful only when `use_deepspeed` flag is passed). "
435
+ "If unspecified, will default to `2`.",
436
+ )
437
+ deepspeed_args.add_argument(
438
+ "--offload_optimizer_device",
439
+ default=None,
440
+ type=str,
441
+ help="Decides where (none|cpu|nvme) to offload optimizer states (useful only when `use_deepspeed` flag is passed). "
442
+ "If unspecified, will default to 'none'.",
443
+ )
444
+ deepspeed_args.add_argument(
445
+ "--offload_param_device",
446
+ default=None,
447
+ type=str,
448
+ help="Decides where (none|cpu|nvme) to offload parameters (useful only when `use_deepspeed` flag is passed). "
449
+ "If unspecified, will default to 'none'.",
450
+ )
451
+ deepspeed_args.add_argument(
452
+ "--offload_optimizer_nvme_path",
453
+ default=None,
454
+ type=str,
455
+ help="Decides Nvme Path to offload optimizer states (useful only when `use_deepspeed` flag is passed). "
456
+ "If unspecified, will default to 'none'.",
457
+ )
458
+ deepspeed_args.add_argument(
459
+ "--offload_param_nvme_path",
460
+ default=None,
461
+ type=str,
462
+ help="Decides Nvme Path to offload parameters (useful only when `use_deepspeed` flag is passed). "
463
+ "If unspecified, will default to 'none'.",
464
+ )
465
+ deepspeed_args.add_argument(
466
+ "--gradient_accumulation_steps",
467
+ default=None,
468
+ type=int,
469
+ help="No of gradient_accumulation_steps used in your training script (useful only when `use_deepspeed` flag is passed). "
470
+ "If unspecified, will default to `1`.",
471
+ )
472
+ deepspeed_args.add_argument(
473
+ "--gradient_clipping",
474
+ default=None,
475
+ type=float,
476
+ help="gradient clipping value used in your training script (useful only when `use_deepspeed` flag is passed). "
477
+ "If unspecified, will default to `1.0`.",
478
+ )
479
+ deepspeed_args.add_argument(
480
+ "--zero3_init_flag",
481
+ default=None,
482
+ type=str,
483
+ help="Decides Whether (true|false) to enable `deepspeed.zero.Init` for constructing massive models. "
484
+ "Only applicable with DeepSpeed ZeRO Stage-3. If unspecified, will default to `true`.",
485
+ )
486
+ deepspeed_args.add_argument(
487
+ "--zero3_save_16bit_model",
488
+ default=None,
489
+ type=str,
490
+ help="Decides Whether (true|false) to save 16-bit model weights when using ZeRO Stage-3. "
491
+ "Only applicable with DeepSpeed ZeRO Stage-3. If unspecified, will default to `false`.",
492
+ )
493
+ deepspeed_args.add_argument(
494
+ "--deepspeed_hostfile",
495
+ default=None,
496
+ type=str,
497
+ help="DeepSpeed hostfile for configuring multi-node compute resources.",
498
+ )
499
+ deepspeed_args.add_argument(
500
+ "--deepspeed_exclusion_filter",
501
+ default=None,
502
+ type=str,
503
+ help="DeepSpeed exclusion filter string when using mutli-node setup.",
504
+ )
505
+ deepspeed_args.add_argument(
506
+ "--deepspeed_inclusion_filter",
507
+ default=None,
508
+ type=str,
509
+ help="DeepSpeed inclusion filter string when using mutli-node setup.",
510
+ )
511
+ deepspeed_args.add_argument(
512
+ "--deepspeed_multinode_launcher",
513
+ default=None,
514
+ type=str,
515
+ 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`.",
516
+ )
517
+ deepspeed_args.add_argument(
518
+ "--deepspeed_moe_layer_cls_names",
519
+ default=None,
520
+ type=str,
521
+ help="comma-separated list of transformer MoE layer class names (case-sensitive) to wrap ,e.g, `MixtralSparseMoeBlock`, `Qwen2MoeSparseMoeBlock`, `JetMoEAttention,JetMoEBlock` ..."
522
+ " (useful only when `use_deepspeed` flag is passed).",
523
+ )
524
+
525
+ # fsdp arguments
526
+ fsdp_args = parser.add_argument_group("FSDP Arguments", "Arguments related to Fully Shared Data Parallelism.")
527
+ fsdp_args.add_argument(
528
+ "--fsdp_version",
529
+ type=str,
530
+ default="1",
531
+ choices=["1", "2"],
532
+ help="FSDP version to use. (useful only when `use_fsdp` flag is passed).",
533
+ )
534
+ fsdp_args.add_argument(
535
+ "--fsdp_offload_params",
536
+ default="false",
537
+ type=str,
538
+ help="Decides Whether (true|false) to offload parameters and gradients to CPU. (useful only when `use_fsdp` flag is passed).",
539
+ )
540
+ fsdp_args.add_argument(
541
+ "--fsdp_min_num_params",
542
+ type=int,
543
+ default=1e8,
544
+ help="FSDP's minimum number of parameters for Default Auto Wrapping. (useful only when `use_fsdp` flag is passed).",
545
+ )
546
+ # We enable this for backwards compatibility, throw a warning if this is set in `FullyShardedDataParallelPlugin`
547
+ fsdp_args.add_argument(
548
+ "--fsdp_sharding_strategy",
549
+ type=str,
550
+ default="FULL_SHARD",
551
+ help="FSDP's sharding strategy. (useful only when `use_fsdp` flag is passed and `fsdp_version=1`).",
552
+ )
553
+ fsdp_args.add_argument(
554
+ "--fsdp_reshard_after_forward",
555
+ type=str,
556
+ default="true",
557
+ 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).",
558
+ )
559
+ fsdp_args.add_argument(
560
+ "--fsdp_auto_wrap_policy",
561
+ type=str,
562
+ default=None,
563
+ help="FSDP's auto wrap policy. (useful only when `use_fsdp` flag is passed).",
564
+ )
565
+ fsdp_args.add_argument(
566
+ "--fsdp_transformer_layer_cls_to_wrap",
567
+ default=None,
568
+ type=str,
569
+ help="Transformer layer class name (case-sensitive) to wrap ,e.g, `BertLayer`, `GPTJBlock`, `T5Block` .... "
570
+ "(useful only when `use_fsdp` flag is passed).",
571
+ )
572
+ fsdp_args.add_argument(
573
+ "--fsdp_backward_prefetch",
574
+ default=None,
575
+ type=str,
576
+ help="FSDP's backward prefetch policy. (useful only when `use_fsdp` flag is passed).",
577
+ )
578
+ fsdp_args.add_argument(
579
+ "--fsdp_state_dict_type",
580
+ default=None,
581
+ type=str,
582
+ help="FSDP's state dict type. (useful only when `use_fsdp` flag is passed).",
583
+ )
584
+ fsdp_args.add_argument(
585
+ "--fsdp_forward_prefetch",
586
+ default="false",
587
+ type=str,
588
+ help="If True, then FSDP explicitly prefetches the next upcoming "
589
+ "all-gather while executing in the forward pass (useful only when `use_fsdp` flag is passed).",
590
+ )
591
+ fsdp_args.add_argument(
592
+ "--fsdp_use_orig_params",
593
+ default="true",
594
+ type=str,
595
+ help="If True, allows non-uniform `requires_grad` during init, which means support for interspersed frozen and trainable paramteres."
596
+ " (useful only when `use_fsdp` flag is passed).",
597
+ )
598
+ fsdp_args.add_argument(
599
+ "--fsdp_cpu_ram_efficient_loading",
600
+ default="true",
601
+ type=str,
602
+ help="If True, only the first process loads the pretrained model checkoint while all other processes have empty weights. "
603
+ "Only applicable for 🤗 Transformers. When using this, `--fsdp_sync_module_states` needs to True. "
604
+ "(useful only when `use_fsdp` flag is passed).",
605
+ )
606
+ fsdp_args.add_argument(
607
+ "--fsdp_sync_module_states",
608
+ default="true",
609
+ type=str,
610
+ help="If True, each individually wrapped FSDP unit will broadcast module parameters from rank 0."
611
+ " (useful only when `use_fsdp` flag is passed).",
612
+ )
613
+ fsdp_args.add_argument(
614
+ "--fsdp_activation_checkpointing",
615
+ default="false",
616
+ type=str,
617
+ 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).",
618
+ )
619
+
620
+ # megatron_lm args
621
+ megatron_lm_args = parser.add_argument_group("Megatron-LM Arguments", "Arguments related to Megatron-LM.")
622
+ megatron_lm_args.add_argument(
623
+ "--megatron_lm_tp_degree",
624
+ type=int,
625
+ default=1,
626
+ help="Megatron-LM's Tensor Parallelism (TP) degree. (useful only when `use_megatron_lm` flag is passed).",
627
+ )
628
+ megatron_lm_args.add_argument(
629
+ "--megatron_lm_pp_degree",
630
+ type=int,
631
+ default=1,
632
+ help="Megatron-LM's Pipeline Parallelism (PP) degree. (useful only when `use_megatron_lm` flag is passed).",
633
+ )
634
+ megatron_lm_args.add_argument(
635
+ "--megatron_lm_num_micro_batches",
636
+ type=int,
637
+ default=None,
638
+ help="Megatron-LM's number of micro batches when PP degree > 1. (useful only when `use_megatron_lm` flag is passed).",
639
+ )
640
+ megatron_lm_args.add_argument(
641
+ "--megatron_lm_sequence_parallelism",
642
+ default=None,
643
+ type=str,
644
+ help="Decides Whether (true|false) to enable Sequence Parallelism when TP degree > 1. "
645
+ "(useful only when `use_megatron_lm` flag is passed).",
646
+ )
647
+ megatron_lm_args.add_argument(
648
+ "--megatron_lm_recompute_activations",
649
+ default=None,
650
+ type=str,
651
+ help="Decides Whether (true|false) to enable Selective Activation Recomputation. "
652
+ "(useful only when `use_megatron_lm` flag is passed).",
653
+ )
654
+ megatron_lm_args.add_argument(
655
+ "--megatron_lm_use_distributed_optimizer",
656
+ default=None,
657
+ type=str,
658
+ help="Decides Whether (true|false) to use distributed optimizer "
659
+ "which shards optimizer state and gradients across Data Pralellel (DP) ranks. "
660
+ "(useful only when `use_megatron_lm` flag is passed).",
661
+ )
662
+ megatron_lm_args.add_argument(
663
+ "--megatron_lm_gradient_clipping",
664
+ default=1.0,
665
+ type=float,
666
+ help="Megatron-LM's gradient clipping value based on global L2 Norm (0 to disable). "
667
+ "(useful only when `use_megatron_lm` flag is passed).",
668
+ )
669
+
670
+ # FP8 arguments
671
+ fp8_args = parser.add_argument_group(
672
+ "FP8 Arguments", "Arguments related to FP8 training (requires `--mixed_precision=fp8`)"
673
+ )
674
+ fp8_args.add_argument(
675
+ "--fp8_backend",
676
+ type=str,
677
+ choices=["te", "msamp"],
678
+ help="Choose a backend to train with FP8 (te: TransformerEngine, msamp: MS-AMP)",
679
+ )
680
+ fp8_args.add_argument(
681
+ "--fp8_use_autocast_during_eval",
682
+ default=False,
683
+ action="store_true",
684
+ 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.",
685
+ )
686
+ fp8_args.add_argument(
687
+ "--fp8_margin",
688
+ type=int,
689
+ default=0,
690
+ help="The margin to use for the gradient scaling (useful only when `--fp8_backend=te` is passed).",
691
+ )
692
+ fp8_args.add_argument(
693
+ "--fp8_interval",
694
+ type=int,
695
+ default=1,
696
+ help="The interval to use for how often the scaling factor is recomputed (useful only when `--fp8_backend=te` is passed).",
697
+ )
698
+ fp8_args.add_argument(
699
+ "--fp8_format",
700
+ type=str,
701
+ default="HYBRID",
702
+ choices=["HYBRID", "E4M3", "E5M2"],
703
+ help="The format to use for the FP8 recipe (useful only when `--fp8_backend=te` is passed).",
704
+ )
705
+ fp8_args.add_argument(
706
+ "--fp8_amax_history_len",
707
+ type=int,
708
+ default=1024,
709
+ help="The length of the history to use for the scaling factor computation (useful only when `--fp8_backend=te` is passed).",
710
+ )
711
+ fp8_args.add_argument(
712
+ "--fp8_amax_compute_algo",
713
+ type=str,
714
+ default="most_recent",
715
+ choices=["max", "most_recent"],
716
+ help="The algorithm to use for the scaling factor computation. (useful only when `--fp8_backend=te` is passed).",
717
+ )
718
+ fp8_args.add_argument(
719
+ "--fp8_override_linear_precision",
720
+ type=lambda x: tuple(map(str_to_bool, x.split(","))),
721
+ default=(False, False, False),
722
+ 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).",
723
+ )
724
+ fp8_args.add_argument(
725
+ "--fp8_opt_level",
726
+ type=str,
727
+ default="O2",
728
+ choices=["O1", "O2"],
729
+ help="What level of 8-bit collective communication should be used with MS-AMP (useful only when `--fp8_backend=msamp` is passed).",
730
+ )
731
+
732
+ # AWS arguments
733
+ aws_args = parser.add_argument_group("AWS Arguments", "Arguments related to AWS.")
734
+ aws_args.add_argument(
735
+ "--aws_access_key_id",
736
+ type=str,
737
+ default=None,
738
+ help="The AWS_ACCESS_KEY_ID used to launch the Amazon SageMaker training job",
739
+ )
740
+ aws_args.add_argument(
741
+ "--aws_secret_access_key",
742
+ type=str,
743
+ default=None,
744
+ help="The AWS_SECRET_ACCESS_KEY used to launch the Amazon SageMaker training job.",
745
+ )
746
+ parser.add_argument(
747
+ "--debug",
748
+ action="store_true",
749
+ help="Whether to print out the torch.distributed stack trace when something fails.",
750
+ )
751
+ parser.add_argument(
752
+ "training_script",
753
+ type=str,
754
+ help=(
755
+ "The full path to the script to be launched in parallel, followed by all the arguments for the training "
756
+ "script."
757
+ ),
758
+ )
759
+
760
+ # MPI arguments
761
+ mpirun_args = parser.add_argument_group("MPI Arguments", "Arguments related to mpirun for Multi-CPU")
762
+ mpirun_args.add_argument(
763
+ "--mpirun_hostfile",
764
+ type=str,
765
+ default=None,
766
+ help="Location for a hostfile for using Accelerate to launch a multi-CPU training job with mpirun. This will "
767
+ "get passed to the MPI --hostfile or -f parameter, depending on which MPI program is installed.",
768
+ )
769
+ mpirun_args.add_argument(
770
+ "--mpirun_ccl",
771
+ type=int,
772
+ default=1,
773
+ help="The number of oneCCL worker threads when using Accelerate to launch multi-CPU training with mpirun.",
774
+ )
775
+
776
+ # ParallelismConfig arguments
777
+ parallelism_config_args = parser.add_argument_group(
778
+ "ParallelismConfig Arguments",
779
+ "Arguments related to the ParallelismConfig used for distributed training.",
780
+ )
781
+ parallelism_config_args.add_argument(
782
+ "--parallelism_config_dp_replicate_size",
783
+ type=int,
784
+ default=1,
785
+ help="The number of processes for data parallel training. Defaults to 1 (no data parallelism).",
786
+ )
787
+
788
+ parallelism_config_args.add_argument(
789
+ "--parallelism_config_dp_shard_size",
790
+ type=int,
791
+ default=1,
792
+ help="The number of processes for FSDP sharding. Defaults to 1 (No FSDP sharding).",
793
+ )
794
+
795
+ parallelism_config_args.add_argument(
796
+ "--parallelism_config_tp_size",
797
+ type=int,
798
+ default=1,
799
+ help="The number of processes for tensor parallel training. Defaults to 1 (no tensor parallelism).",
800
+ )
801
+
802
+ parallelism_config_args.add_argument(
803
+ "--parallelism_config_cp_size",
804
+ type=int,
805
+ default=1,
806
+ help="The number of processese for context parallel training. Defaults to 1 (no context parallelism).",
807
+ )
808
+ parallelism_config_args.add_argument(
809
+ "--parallelism_config_cp_comm_strategy",
810
+ type=str,
811
+ default="allgather",
812
+ help="The communication strategy for context parallel training. Defaults to 'allgather'. Other option is alltoall",
813
+ )
814
+
815
+ # Other arguments of the training scripts
816
+ parser.add_argument("training_script_args", nargs=argparse.REMAINDER, help="Arguments of the training script.")
817
+
818
+ if subparsers is not None:
819
+ parser.set_defaults(func=launch_command)
820
+ return parser
821
+
822
+
823
+ def simple_launcher(args):
824
+ cmd, current_env = prepare_simple_launcher_cmd_env(args)
825
+
826
+ process = subprocess.Popen(cmd, env=current_env)
827
+ process.wait()
828
+ if process.returncode != 0:
829
+ if not args.quiet:
830
+ raise subprocess.CalledProcessError(returncode=process.returncode, cmd=cmd)
831
+ else:
832
+ sys.exit(1)
833
+
834
+
835
+ def multi_gpu_launcher(args):
836
+ import torch.distributed.run as distrib_run
837
+
838
+ current_env = prepare_multi_gpu_env(args)
839
+ if not check_cuda_p2p_ib_support():
840
+ message = "Using RTX 4000 series which doesn't support faster communication speedups. Ensuring P2P and IB communications are disabled."
841
+ warn = False
842
+ if "NCCL_P2P_DISABLE" not in current_env:
843
+ current_env["NCCL_P2P_DISABLE"] = "1"
844
+ warn = True
845
+ if "NCCL_IB_DISABLE" not in current_env:
846
+ current_env["NCCL_IB_DISABLE"] = "1"
847
+ warn = True
848
+ if warn:
849
+ logger.warning(message)
850
+
851
+ debug = getattr(args, "debug", False)
852
+ args = _filter_args(
853
+ args,
854
+ distrib_run.get_args_parser(),
855
+ ["--training_script", args.training_script, "--training_script_args", args.training_script_args],
856
+ )
857
+
858
+ with patch_environment(**current_env):
859
+ try:
860
+ distrib_run.run(args)
861
+ except Exception:
862
+ if is_rich_available() and debug:
863
+ console = get_console()
864
+ console.print("\n[bold red]Using --debug, `torch.distributed` Stack Trace:[/bold red]")
865
+ console.print_exception(suppress=[__file__], show_locals=False)
866
+ else:
867
+ raise
868
+
869
+
870
+ def deepspeed_launcher(args):
871
+ import torch.distributed.run as distrib_run
872
+
873
+ if not is_deepspeed_available():
874
+ raise ImportError("DeepSpeed is not installed => run `pip3 install deepspeed` or build it from source.")
875
+ else:
876
+ from deepspeed.launcher.runner import DEEPSPEED_ENVIRONMENT_NAME
877
+
878
+ cmd, current_env = prepare_deepspeed_cmd_env(args)
879
+ if not check_cuda_p2p_ib_support():
880
+ message = "Using RTX 4000 series which doesn't support faster communication speedups. Ensuring P2P and IB communications are disabled."
881
+ warn = False
882
+ if "NCCL_P2P_DISABLE" not in current_env:
883
+ current_env["NCCL_P2P_DISABLE"] = "1"
884
+ warn = True
885
+ if "NCCL_IB_DISABLE" not in current_env:
886
+ current_env["NCCL_IB_DISABLE"] = "1"
887
+ warn = True
888
+ if warn:
889
+ logger.warning(message)
890
+
891
+ if args.num_machines > 1 and args.deepspeed_multinode_launcher != DEEPSPEED_MULTINODE_LAUNCHERS[1]:
892
+ with open(DEEPSPEED_ENVIRONMENT_NAME, "a") as f:
893
+ valid_env_items = convert_dict_to_env_variables(current_env)
894
+ if len(valid_env_items) > 1:
895
+ f.writelines(valid_env_items)
896
+
897
+ process = subprocess.Popen(cmd, env=current_env)
898
+ process.wait()
899
+ if process.returncode != 0:
900
+ if not args.quiet:
901
+ raise subprocess.CalledProcessError(returncode=process.returncode, cmd=cmd)
902
+ else:
903
+ sys.exit(1)
904
+ else:
905
+ debug = getattr(args, "debug", False)
906
+ args = _filter_args(
907
+ args,
908
+ distrib_run.get_args_parser(),
909
+ ["--training_script", args.training_script, "--training_script_args", args.training_script_args],
910
+ )
911
+ with patch_environment(**current_env):
912
+ try:
913
+ distrib_run.run(args)
914
+ except Exception:
915
+ if is_rich_available() and debug:
916
+ console = get_console()
917
+ console.print("\n[bold red]Using --debug, `torch.distributed` Stack Trace:[/bold red]")
918
+ console.print_exception(suppress=[__file__], show_locals=False)
919
+ else:
920
+ raise
921
+
922
+
923
+ def tpu_launcher(args):
924
+ import torch_xla.distributed.xla_multiprocessing as xmp
925
+
926
+ if args.no_python:
927
+ raise ValueError("--no_python cannot be used with TPU launcher")
928
+
929
+ args, current_env = prepare_tpu(args, {})
930
+
931
+ if args.module:
932
+ mod_name = args.training_script
933
+ else:
934
+ # Import training_script as a module
935
+ script_path = Path(args.training_script)
936
+ sys.path.append(str(script_path.parent.resolve()))
937
+ mod_name = script_path.stem
938
+
939
+ mod = importlib.import_module(mod_name)
940
+ if not hasattr(mod, args.main_training_function):
941
+ raise ValueError(
942
+ f"Your training script should have a function named {args.main_training_function}, or you should pass a "
943
+ "different value to `--main_training_function`."
944
+ )
945
+
946
+ # Patch sys.argv
947
+ sys.argv = [mod.__file__] + args.training_script_args
948
+
949
+ main_function = getattr(mod, args.main_training_function)
950
+ with patch_environment(**current_env):
951
+ xmp.spawn(PrepareForLaunch(main_function), args=())
952
+
953
+
954
+ def tpu_pod_launcher(args):
955
+ from torch_xla.distributed import xla_dist
956
+
957
+ current_env = {}
958
+ args, current_env = prepare_tpu(args, current_env, True)
959
+ debug = getattr(args, "debug", False)
960
+
961
+ training_script = args.training_script
962
+ training_script_args = args.training_script_args
963
+ new_args = _filter_args(
964
+ args, xla_dist.get_args_parser(), ["--tpu", args.tpu_name, "--positional", "", "--restart-tpuvm-pod-server"]
965
+ )
966
+
967
+ if args.tpu_use_sudo:
968
+ new_cmd = ["sudo"]
969
+ else:
970
+ new_cmd = []
971
+
972
+ new_cmd += [
973
+ "accelerate-launch",
974
+ "--tpu",
975
+ "--no_tpu_cluster",
976
+ "--num_machines",
977
+ "1",
978
+ "--mixed_precision",
979
+ "no",
980
+ "--dynamo_backend",
981
+ "no",
982
+ "--num_processes",
983
+ str(args.num_processes),
984
+ "--main_training_function",
985
+ str(args.main_training_function),
986
+ training_script,
987
+ ] + training_script_args
988
+
989
+ new_args.positional = new_cmd
990
+ bad_flags = ""
991
+ for arg in vars(new_args):
992
+ if arg.startswith("docker_"):
993
+ value = getattr(new_args, arg)
994
+ if value != "" and value is not None:
995
+ bad_flags += f'{arg}="{value}"\n'
996
+ if bad_flags != "":
997
+ raise ValueError(
998
+ f"Docker containers are not supported for TPU pod launcher currently, please remove the following flags:\n{bad_flags}"
999
+ )
1000
+ new_args.env = [f"{k}={v}" for k, v in current_env.items()]
1001
+ new_args.env.append("ACCELERATE_IN_TPU_POD=1")
1002
+ try:
1003
+ xla_dist.resolve_and_execute(new_args)
1004
+ except Exception:
1005
+ if is_rich_available() and debug:
1006
+ console = get_console()
1007
+ console.print("\n[bold red]Using --debug, `torch_xla.xla_dist` Stack Trace:[/bold red]")
1008
+ console.print_exception(suppress=[__file__], show_locals=False)
1009
+ else:
1010
+ raise
1011
+
1012
+
1013
+ def sagemaker_launcher(sagemaker_config: SageMakerConfig, args):
1014
+ if not is_sagemaker_available():
1015
+ raise ImportError(
1016
+ "Please install sagemaker to be able to launch training on Amazon SageMaker with `pip install accelerate[sagemaker]`"
1017
+ )
1018
+ if args.module or args.no_python:
1019
+ raise ValueError(
1020
+ "SageMaker requires a python training script file and cannot be used with --module or --no_python"
1021
+ )
1022
+
1023
+ from sagemaker.huggingface import HuggingFace
1024
+
1025
+ args, sagemaker_inputs = prepare_sagemager_args_inputs(sagemaker_config, args)
1026
+
1027
+ huggingface_estimator = HuggingFace(**args)
1028
+
1029
+ huggingface_estimator.fit(inputs=sagemaker_inputs)
1030
+ print(f"You can find your model data at: {huggingface_estimator.model_data}")
1031
+
1032
+
1033
+ def _validate_launch_command(args):
1034
+ # Sanity checks
1035
+ if sum([args.multi_gpu, args.cpu, args.tpu, args.use_deepspeed, args.use_fsdp]) > 1:
1036
+ raise ValueError(
1037
+ "You can only use one of `--cpu`, `--multi_gpu`, `--tpu`, `--use_deepspeed`, `--use_fsdp` at a time."
1038
+ )
1039
+ if args.multi_gpu and (args.num_processes is not None) and (args.num_processes < 2):
1040
+ raise ValueError("You need to use at least 2 processes to use `--multi_gpu`.")
1041
+
1042
+ if (not args.use_fsdp or args.fsdp_version == 1) and args.use_parallelism_config:
1043
+ raise ValueError("You cannot use `--use_parallelism_config` without `--use_fsdp` and `--fsdp_version=2`. ")
1044
+
1045
+ defaults = None
1046
+ warned = []
1047
+ mp_from_config_flag = False
1048
+ # Get the default from the config file.
1049
+ if args.config_file is not None or os.path.isfile(default_config_file) and not args.cpu:
1050
+ defaults = load_config_from_file(args.config_file)
1051
+ if (
1052
+ not args.multi_gpu
1053
+ and not args.tpu
1054
+ and not args.tpu_use_cluster
1055
+ and not args.use_deepspeed
1056
+ and not args.use_fsdp
1057
+ and not args.use_megatron_lm
1058
+ ):
1059
+ args.use_deepspeed = defaults.distributed_type == DistributedType.DEEPSPEED
1060
+ args.multi_gpu = (
1061
+ True
1062
+ if defaults.distributed_type
1063
+ in (
1064
+ DistributedType.MULTI_GPU,
1065
+ DistributedType.MULTI_NPU,
1066
+ DistributedType.MULTI_MLU,
1067
+ DistributedType.MULTI_SDAA,
1068
+ DistributedType.MULTI_MUSA,
1069
+ DistributedType.MULTI_XPU,
1070
+ DistributedType.MULTI_HPU,
1071
+ )
1072
+ else False
1073
+ )
1074
+ args.tpu = defaults.distributed_type == DistributedType.XLA
1075
+ args.use_fsdp = defaults.distributed_type == DistributedType.FSDP
1076
+ args.use_megatron_lm = defaults.distributed_type == DistributedType.MEGATRON_LM
1077
+ args.tpu_use_cluster = defaults.tpu_use_cluster if args.tpu else False
1078
+ args.use_parallelism_config = defaults.parallelism_config != {}
1079
+ if args.gpu_ids is None:
1080
+ if defaults.gpu_ids is not None:
1081
+ args.gpu_ids = defaults.gpu_ids
1082
+ else:
1083
+ args.gpu_ids = "all"
1084
+
1085
+ if args.multi_gpu and args.num_machines is None:
1086
+ args.num_machines = defaults.num_machines
1087
+
1088
+ if len(args.gpu_ids.split(",")) < 2 and (args.gpu_ids != "all") and args.multi_gpu and args.num_machines <= 1:
1089
+ raise ValueError(
1090
+ "Less than two GPU ids were configured and tried to run on on multiple GPUs. "
1091
+ "Please ensure at least two are specified for `--gpu_ids`, or use `--gpu_ids='all'`."
1092
+ )
1093
+ if defaults.compute_environment == ComputeEnvironment.LOCAL_MACHINE:
1094
+ # Update args with the defaults
1095
+ for name, attr in defaults.__dict__.items():
1096
+ if isinstance(attr, dict):
1097
+ # Copy defaults.somedict.somearg to args.somearg and
1098
+ # defaults.fsdp_config.x to args.fsdp_x
1099
+ for key, value in attr.items():
1100
+ if name == "fsdp_config" and not key.startswith("fsdp"):
1101
+ key = "fsdp_" + key
1102
+ elif name == "fp8_config" and not key.startswith("fp8"):
1103
+ key = "fp8_" + key
1104
+ if hasattr(args, "nondefault") and key not in args.nondefault:
1105
+ setattr(args, key, value)
1106
+ elif (
1107
+ name not in ["compute_environment", "mixed_precision", "distributed_type"]
1108
+ and getattr(args, name, None) is None
1109
+ ):
1110
+ # Those args are handled separately
1111
+ setattr(args, name, attr)
1112
+ if not args.debug:
1113
+ args.debug = defaults.debug
1114
+
1115
+ if not args.mixed_precision:
1116
+ if defaults.mixed_precision is None:
1117
+ args.mixed_precision = "no"
1118
+ else:
1119
+ args.mixed_precision = defaults.mixed_precision
1120
+ mp_from_config_flag = True
1121
+ else:
1122
+ native_amp = is_bf16_available(True)
1123
+ if (
1124
+ args.mixed_precision == "bf16"
1125
+ and not native_amp
1126
+ and not (args.tpu and is_torch_xla_available(check_is_tpu=True))
1127
+ ):
1128
+ raise ValueError("bf16 mixed precision requires PyTorch >= 1.10 and a supported device.")
1129
+
1130
+ # Silently set the default here
1131
+ if args.dynamo_backend is None:
1132
+ args.dynamo_backend = "no"
1133
+ if args.num_processes == -1:
1134
+ raise ValueError("You need to manually pass in `--num_processes` using this config yaml.")
1135
+ else:
1136
+ if args.num_processes is None:
1137
+ if is_xpu_available():
1138
+ args.num_processes = torch.xpu.device_count()
1139
+ elif is_mlu_available():
1140
+ args.num_processes = torch.mlu.device_count()
1141
+ elif is_sdaa_available():
1142
+ args.num_processes = torch.sdaa.device_count()
1143
+ elif is_musa_available():
1144
+ args.num_processes = torch.musa.device_count()
1145
+ elif is_npu_available():
1146
+ args.num_processes = torch.npu.device_count()
1147
+ elif is_hpu_available():
1148
+ args.num_processes = torch.hpu.device_count()
1149
+ else:
1150
+ args.num_processes = torch.cuda.device_count()
1151
+ warned.append(f"\t`--num_processes` was set to a value of `{args.num_processes}`")
1152
+ if args.debug is None:
1153
+ args.debug = False
1154
+ if (
1155
+ not args.multi_gpu
1156
+ and args.num_processes > 1
1157
+ and (
1158
+ (is_xpu_available() and torch.xpu.device_count() > 1)
1159
+ or (is_npu_available() and torch.npu.device_count() > 1)
1160
+ or (is_hpu_available() and torch.hpu.device_count() > 1)
1161
+ or (is_mlu_available() and torch.mlu.device_count() > 1)
1162
+ or (is_sdaa_available() and torch.sdaa.device_count() > 1)
1163
+ or (is_musa_available() and torch.musa.device_count() > 1)
1164
+ or (torch.cuda.is_available() and torch.cuda.device_count() > 1)
1165
+ )
1166
+ ):
1167
+ warned.append(
1168
+ "\t\tMore than one GPU was found, enabling multi-GPU training.\n"
1169
+ "\t\tIf this was unintended please pass in `--num_processes=1`."
1170
+ )
1171
+ args.multi_gpu = True
1172
+ if args.num_machines is None:
1173
+ warned.append("\t`--num_machines` was set to a value of `1`")
1174
+ args.num_machines = 1
1175
+ if args.mixed_precision is None:
1176
+ warned.append("\t`--mixed_precision` was set to a value of `'no'`")
1177
+ args.mixed_precision = "no"
1178
+ if not hasattr(args, "use_cpu"):
1179
+ args.use_cpu = args.cpu
1180
+ if args.dynamo_backend is None:
1181
+ warned.append("\t`--dynamo_backend` was set to a value of `'no'`")
1182
+ args.dynamo_backend = "no"
1183
+ if args.debug:
1184
+ logger.debug("Running script in debug mode, expect distributed operations to be slightly slower.")
1185
+
1186
+ is_aws_env_disabled = defaults is None or (
1187
+ defaults is not None and defaults.compute_environment != ComputeEnvironment.AMAZON_SAGEMAKER
1188
+ )
1189
+ if is_aws_env_disabled and args.num_cpu_threads_per_process is None:
1190
+ args.num_cpu_threads_per_process = get_int_from_env(["OMP_NUM_THREADS"], 1)
1191
+ if args.use_cpu and args.num_processes >= 1 and get_int_from_env(["OMP_NUM_THREADS"], 0) == 0:
1192
+ local_size = get_int_from_env(
1193
+ ["MPI_LOCALNRANKS", "OMPI_COMM_WORLD_LOCAL_SIZE", "MV2_COMM_WORLD_LOCAL_SIZE"],
1194
+ max(int(args.num_processes / args.num_machines), 1),
1195
+ )
1196
+ threads_per_process = int(psutil.cpu_count(logical=False) / local_size)
1197
+ if threads_per_process > 1:
1198
+ args.num_cpu_threads_per_process = threads_per_process
1199
+ warned.append(
1200
+ 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"
1201
+ )
1202
+
1203
+ if args.ipex is not None:
1204
+ logger.warning(
1205
+ "ipex flag is deprecated, will be removed in Accelerate v1.10. "
1206
+ "From 2.7.0, PyTorch has all needed optimizations for Intel CPU and XPU."
1207
+ )
1208
+
1209
+ if args.use_xpu is not None:
1210
+ logger.warning(
1211
+ "use_xpu is deprecated and ignored, will be removed in Accelerate v1.20. "
1212
+ "XPU is a PyTorch native citizen now, we don't need extra argument to enable it any more."
1213
+ )
1214
+
1215
+ if any(warned):
1216
+ message = "The following values were not passed to `accelerate launch` and had defaults used instead:\n"
1217
+ message += "\n".join(warned)
1218
+ message += (
1219
+ "\nTo avoid this warning pass in values for each of the problematic parameters or run `accelerate config`."
1220
+ )
1221
+ logger.warning(message)
1222
+ return args, defaults, mp_from_config_flag
1223
+
1224
+
1225
+ def launch_command(args):
1226
+ args, defaults, mp_from_config_flag = _validate_launch_command(args)
1227
+ # Use the proper launcher
1228
+ if args.use_deepspeed and not args.cpu:
1229
+ args.deepspeed_fields_from_accelerate_config = list(defaults.deepspeed_config.keys()) if defaults else []
1230
+ if mp_from_config_flag:
1231
+ args.deepspeed_fields_from_accelerate_config.append("mixed_precision")
1232
+ args.deepspeed_fields_from_accelerate_config = ",".join(args.deepspeed_fields_from_accelerate_config)
1233
+ deepspeed_launcher(args)
1234
+ elif args.use_fsdp and not args.cpu:
1235
+ multi_gpu_launcher(args)
1236
+ elif args.use_megatron_lm and not args.cpu:
1237
+ multi_gpu_launcher(args)
1238
+ elif args.multi_gpu and not args.cpu:
1239
+ multi_gpu_launcher(args)
1240
+ elif args.tpu and not args.cpu:
1241
+ if args.tpu_use_cluster:
1242
+ tpu_pod_launcher(args)
1243
+ else:
1244
+ tpu_launcher(args)
1245
+ elif defaults is not None and defaults.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
1246
+ sagemaker_launcher(defaults, args)
1247
+ else:
1248
+ simple_launcher(args)
1249
+
1250
+
1251
+ def main():
1252
+ parser = launch_command_parser()
1253
+ args = parser.parse_args()
1254
+ launch_command(args)
1255
+
1256
+
1257
+ if __name__ == "__main__":
1258
+ main()
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/menu/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from .selection_menu import BulletMenu
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/menu/cursor.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team and Brian Chao. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ A utility for showing and hiding the terminal cursor on Windows and Linux, based on https://github.com/bchao1/bullet
17
+ """
18
+
19
+ import os
20
+ import sys
21
+ from contextlib import contextmanager
22
+
23
+
24
+ # Windows only
25
+ if os.name == "nt":
26
+ import ctypes
27
+ import msvcrt # noqa
28
+
29
+ class CursorInfo(ctypes.Structure):
30
+ # _fields is a specific attr expected by ctypes
31
+ _fields_ = [("size", ctypes.c_int), ("visible", ctypes.c_byte)]
32
+
33
+
34
+ def hide_cursor():
35
+ if os.name == "nt":
36
+ ci = CursorInfo()
37
+ handle = ctypes.windll.kernel32.GetStdHandle(-11)
38
+ ctypes.windll.kernel32.GetConsoleCursorInfo(handle, ctypes.byref(ci))
39
+ ci.visible = False
40
+ ctypes.windll.kernel32.SetConsoleCursorInfo(handle, ctypes.byref(ci))
41
+ elif os.name == "posix":
42
+ sys.stdout.write("\033[?25l")
43
+ sys.stdout.flush()
44
+
45
+
46
+ def show_cursor():
47
+ if os.name == "nt":
48
+ ci = CursorInfo()
49
+ handle = ctypes.windll.kernel32.GetStdHandle(-11)
50
+ ctypes.windll.kernel32.GetConsoleCursorInfo(handle, ctypes.byref(ci))
51
+ ci.visible = True
52
+ ctypes.windll.kernel32.SetConsoleCursorInfo(handle, ctypes.byref(ci))
53
+ elif os.name == "posix":
54
+ sys.stdout.write("\033[?25h")
55
+ sys.stdout.flush()
56
+
57
+
58
+ @contextmanager
59
+ def hide():
60
+ "Context manager to hide the terminal cursor"
61
+ try:
62
+ hide_cursor()
63
+ yield
64
+ finally:
65
+ show_cursor()
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/menu/helpers.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team and Brian Chao. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ A variety of helper functions and constants when dealing with terminal menu choices, based on
17
+ https://github.com/bchao1/bullet
18
+ """
19
+
20
+ import enum
21
+ import shutil
22
+ import sys
23
+
24
+
25
+ TERMINAL_WIDTH, _ = shutil.get_terminal_size()
26
+
27
+ CURSOR_TO_CHAR = {"UP": "A", "DOWN": "B", "RIGHT": "C", "LEFT": "D"}
28
+
29
+
30
+ class Direction(enum.Enum):
31
+ UP = 0
32
+ DOWN = 1
33
+
34
+
35
+ def forceWrite(content, end=""):
36
+ sys.stdout.write(str(content) + end)
37
+ sys.stdout.flush()
38
+
39
+
40
+ def writeColor(content, color, end=""):
41
+ forceWrite(f"\u001b[{color}m{content}\u001b[0m", end)
42
+
43
+
44
+ def reset_cursor():
45
+ forceWrite("\r")
46
+
47
+
48
+ def move_cursor(num_lines: int, direction: str):
49
+ forceWrite(f"\033[{num_lines}{CURSOR_TO_CHAR[direction.upper()]}")
50
+
51
+
52
+ def clear_line():
53
+ forceWrite(" " * TERMINAL_WIDTH)
54
+ reset_cursor()
55
+
56
+
57
+ def linebreak():
58
+ reset_cursor()
59
+ forceWrite("-" * TERMINAL_WIDTH)
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/menu/input.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team and Brian Chao. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ This file contains utilities for handling input from the user and registering specific keys to specific functions,
17
+ based on https://github.com/bchao1/bullet
18
+ """
19
+
20
+ from .keymap import KEYMAP, get_character
21
+
22
+
23
+ def mark(key: str):
24
+ """
25
+ Mark the function with the key code so it can be handled in the register
26
+ """
27
+
28
+ def decorator(func):
29
+ handle = getattr(func, "handle_key", [])
30
+ handle += [key]
31
+ func.handle_key = handle
32
+ return func
33
+
34
+ return decorator
35
+
36
+
37
+ def mark_multiple(*keys: list[str]):
38
+ """
39
+ Mark the function with the key codes so it can be handled in the register
40
+ """
41
+
42
+ def decorator(func):
43
+ handle = getattr(func, "handle_key", [])
44
+ handle += keys
45
+ func.handle_key = handle
46
+ return func
47
+
48
+ return decorator
49
+
50
+
51
+ class KeyHandler(type):
52
+ """
53
+ Metaclass that adds the key handlers to the class
54
+ """
55
+
56
+ def __new__(cls, name, bases, attrs):
57
+ new_cls = super().__new__(cls, name, bases, attrs)
58
+ if not hasattr(new_cls, "key_handler"):
59
+ new_cls.key_handler = {}
60
+ new_cls.handle_input = KeyHandler.handle_input
61
+
62
+ for value in attrs.values():
63
+ handled_keys = getattr(value, "handle_key", [])
64
+ for key in handled_keys:
65
+ new_cls.key_handler[key] = value
66
+ return new_cls
67
+
68
+ @staticmethod
69
+ def handle_input(cls):
70
+ "Finds and returns the selected character if it exists in the handler"
71
+ char = get_character()
72
+ if char != KEYMAP["undefined"]:
73
+ char = ord(char)
74
+ handler = cls.key_handler.get(char)
75
+ if handler:
76
+ cls.current_selection = char
77
+ return handler(cls)
78
+ else:
79
+ return None
80
+
81
+
82
+ def register(cls):
83
+ """Adds KeyHandler metaclass to the class"""
84
+ return KeyHandler(cls.__name__, cls.__bases__, cls.__dict__.copy())
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/menu/keymap.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team and Brian Chao. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ Utilities relating to parsing raw characters from the keyboard, based on https://github.com/bchao1/bullet
17
+ """
18
+
19
+ import os
20
+ import string
21
+ import sys
22
+
23
+
24
+ ARROW_KEY_FLAG = 1 << 8
25
+
26
+ KEYMAP = {
27
+ "tab": ord("\t"),
28
+ "newline": ord("\r"),
29
+ "esc": 27,
30
+ "up": 65 + ARROW_KEY_FLAG,
31
+ "down": 66 + ARROW_KEY_FLAG,
32
+ "right": 67 + ARROW_KEY_FLAG,
33
+ "left": 68 + ARROW_KEY_FLAG,
34
+ "mod_int": 91,
35
+ "undefined": sys.maxsize,
36
+ "interrupt": 3,
37
+ "insert": 50,
38
+ "delete": 51,
39
+ "pg_up": 53,
40
+ "pg_down": 54,
41
+ }
42
+
43
+ KEYMAP["arrow_begin"] = KEYMAP["up"]
44
+ KEYMAP["arrow_end"] = KEYMAP["left"]
45
+
46
+ if sys.platform == "win32":
47
+ WIN_CH_BUFFER = []
48
+ WIN_KEYMAP = {
49
+ b"\xe0H": KEYMAP["up"] - ARROW_KEY_FLAG,
50
+ b"\x00H": KEYMAP["up"] - ARROW_KEY_FLAG,
51
+ b"\xe0P": KEYMAP["down"] - ARROW_KEY_FLAG,
52
+ b"\x00P": KEYMAP["down"] - ARROW_KEY_FLAG,
53
+ b"\xe0M": KEYMAP["right"] - ARROW_KEY_FLAG,
54
+ b"\x00M": KEYMAP["right"] - ARROW_KEY_FLAG,
55
+ b"\xe0K": KEYMAP["left"] - ARROW_KEY_FLAG,
56
+ b"\x00K": KEYMAP["left"] - ARROW_KEY_FLAG,
57
+ }
58
+
59
+ for i in range(10):
60
+ KEYMAP[str(i)] = ord(str(i))
61
+
62
+
63
+ def get_raw_chars():
64
+ "Gets raw characters from inputs"
65
+ if os.name == "nt":
66
+ import msvcrt
67
+
68
+ encoding = "mbcs"
69
+ # Flush the keyboard buffer
70
+ while msvcrt.kbhit():
71
+ msvcrt.getch()
72
+ if len(WIN_CH_BUFFER) == 0:
73
+ # Read the keystroke
74
+ ch = msvcrt.getch()
75
+
76
+ # If it is a prefix char, get second part
77
+ if ch in (b"\x00", b"\xe0"):
78
+ ch2 = ch + msvcrt.getch()
79
+ # Translate actual Win chars to bullet char types
80
+ try:
81
+ chx = chr(WIN_KEYMAP[ch2])
82
+ WIN_CH_BUFFER.append(chr(KEYMAP["mod_int"]))
83
+ WIN_CH_BUFFER.append(chx)
84
+ if ord(chx) in (
85
+ KEYMAP["insert"] - 1 << 9,
86
+ KEYMAP["delete"] - 1 << 9,
87
+ KEYMAP["pg_up"] - 1 << 9,
88
+ KEYMAP["pg_down"] - 1 << 9,
89
+ ):
90
+ WIN_CH_BUFFER.append(chr(126))
91
+ ch = chr(KEYMAP["esc"])
92
+ except KeyError:
93
+ ch = ch2[1]
94
+ else:
95
+ ch = ch.decode(encoding)
96
+ else:
97
+ ch = WIN_CH_BUFFER.pop(0)
98
+ elif os.name == "posix":
99
+ import termios
100
+ import tty
101
+
102
+ fd = sys.stdin.fileno()
103
+ old_settings = termios.tcgetattr(fd)
104
+ try:
105
+ tty.setraw(fd)
106
+ ch = sys.stdin.read(1)
107
+ finally:
108
+ termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
109
+ return ch
110
+
111
+
112
+ def get_character():
113
+ "Gets a character from the keyboard and returns the key code"
114
+ char = get_raw_chars()
115
+ if ord(char) in [KEYMAP["interrupt"], KEYMAP["newline"]]:
116
+ return char
117
+
118
+ elif ord(char) == KEYMAP["esc"]:
119
+ combo = get_raw_chars()
120
+ if ord(combo) == KEYMAP["mod_int"]:
121
+ key = get_raw_chars()
122
+ if ord(key) >= KEYMAP["arrow_begin"] - ARROW_KEY_FLAG and ord(key) <= KEYMAP["arrow_end"] - ARROW_KEY_FLAG:
123
+ return chr(ord(key) + ARROW_KEY_FLAG)
124
+ else:
125
+ return KEYMAP["undefined"]
126
+ else:
127
+ return get_raw_chars()
128
+
129
+ else:
130
+ if char in string.printable:
131
+ return char
132
+ else:
133
+ return KEYMAP["undefined"]
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/menu/selection_menu.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team and Brian Chao. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ Main driver for the selection menu, based on https://github.com/bchao1/bullet
17
+ """
18
+
19
+ import builtins
20
+ import sys
21
+
22
+ from ...utils.imports import _is_package_available
23
+ from . import cursor, input
24
+ from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor
25
+ from .keymap import KEYMAP
26
+
27
+
28
+ in_colab = False
29
+ try:
30
+ in_colab = _is_package_available("google.colab")
31
+ except ModuleNotFoundError:
32
+ pass
33
+
34
+
35
+ @input.register
36
+ class BulletMenu:
37
+ """
38
+ A CLI menu to select a choice from a list of choices using the keyboard.
39
+ """
40
+
41
+ def __init__(self, prompt: str = None, choices: list = []):
42
+ self.position = 0
43
+ self.choices = choices
44
+ self.prompt = prompt
45
+ if sys.platform == "win32":
46
+ self.arrow_char = "*"
47
+ else:
48
+ self.arrow_char = "➔ "
49
+
50
+ def write_choice(self, index, end: str = ""):
51
+ if sys.platform != "win32":
52
+ writeColor(self.choices[index], 32, end)
53
+ else:
54
+ forceWrite(self.choices[index], end)
55
+
56
+ def print_choice(self, index: int):
57
+ "Prints the choice at the given index"
58
+ if index == self.position:
59
+ forceWrite(f" {self.arrow_char} ")
60
+ self.write_choice(index)
61
+ else:
62
+ forceWrite(f" {self.choices[index]}")
63
+ reset_cursor()
64
+
65
+ def move_direction(self, direction: Direction, num_spaces: int = 1):
66
+ "Should not be directly called, used to move a direction of either up or down"
67
+ old_position = self.position
68
+ if direction == Direction.DOWN:
69
+ if self.position + 1 >= len(self.choices):
70
+ return
71
+ self.position += num_spaces
72
+ else:
73
+ if self.position - 1 < 0:
74
+ return
75
+ self.position -= num_spaces
76
+ clear_line()
77
+ self.print_choice(old_position)
78
+ move_cursor(num_spaces, direction.name)
79
+ self.print_choice(self.position)
80
+
81
+ @input.mark(KEYMAP["up"])
82
+ def move_up(self):
83
+ self.move_direction(Direction.UP)
84
+
85
+ @input.mark(KEYMAP["down"])
86
+ def move_down(self):
87
+ self.move_direction(Direction.DOWN)
88
+
89
+ @input.mark(KEYMAP["newline"])
90
+ def select(self):
91
+ move_cursor(len(self.choices) - self.position, "DOWN")
92
+ return self.position
93
+
94
+ @input.mark(KEYMAP["interrupt"])
95
+ def interrupt(self):
96
+ move_cursor(len(self.choices) - self.position, "DOWN")
97
+ raise KeyboardInterrupt
98
+
99
+ @input.mark_multiple(*[KEYMAP[str(number)] for number in range(10)])
100
+ def select_row(self):
101
+ index = int(chr(self.current_selection))
102
+ movement = index - self.position
103
+ if index == self.position:
104
+ return
105
+ if index < len(self.choices):
106
+ if self.position > index:
107
+ self.move_direction(Direction.UP, -movement)
108
+ elif self.position < index:
109
+ self.move_direction(Direction.DOWN, movement)
110
+ else:
111
+ return
112
+ else:
113
+ return
114
+
115
+ def run(self, default_choice: int = 0):
116
+ "Start the menu and return the selected choice"
117
+ if self.prompt:
118
+ linebreak()
119
+ forceWrite(self.prompt, "\n")
120
+ if in_colab:
121
+ forceWrite("Please input a choice index (starting from 0), and press enter", "\n")
122
+ else:
123
+ forceWrite("Please select a choice using the arrow or number keys, and selecting with enter", "\n")
124
+ self.position = default_choice
125
+ for i in range(len(self.choices)):
126
+ self.print_choice(i)
127
+ forceWrite("\n")
128
+ move_cursor(len(self.choices) - self.position, "UP")
129
+ with cursor.hide():
130
+ while True:
131
+ if in_colab:
132
+ try:
133
+ choice = int(builtins.input())
134
+ except ValueError:
135
+ choice = default_choice
136
+ else:
137
+ choice = self.handle_input()
138
+ if choice is not None:
139
+ reset_cursor()
140
+ for _ in range(len(self.choices) + 1):
141
+ move_cursor(1, "UP")
142
+ clear_line()
143
+ self.write_choice(choice, "\n")
144
+ return choice
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/merge.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ from accelerate.commands.utils import CustomArgumentParser
17
+ from accelerate.utils import merge_fsdp_weights
18
+
19
+
20
+ description = """Utility to merge the weights from multiple FSDP checkpoints into a single combined checkpoint. Should be used if
21
+ `SHARDED_STATE_DICT` was used for the model. Weights will be saved to `{output_path}`.
22
+
23
+ This is a CPU-bound process and requires enough RAM to load the entire model state dict."""
24
+
25
+
26
+ def merge_command(args):
27
+ merge_fsdp_weights(
28
+ args.checkpoint_directory, args.output_path, not args.unsafe_serialization, args.remove_checkpoint_dir
29
+ )
30
+
31
+
32
+ def merge_command_parser(subparsers=None):
33
+ if subparsers is not None:
34
+ parser = subparsers.add_parser("merge-weights", description=description)
35
+ else:
36
+ parser = CustomArgumentParser(description=description)
37
+
38
+ parser.add_argument("checkpoint_directory", type=str, help="A directory containing sharded weights saved by FSDP.")
39
+ parser.add_argument(
40
+ "output_path",
41
+ type=str,
42
+ help="The path to save the merged weights. Defaults to the current directory. ",
43
+ )
44
+ parser.add_argument(
45
+ "--unsafe_serialization",
46
+ action="store_true",
47
+ default=False,
48
+ help="Whether to save the merged weights as `.bin` rather than `.safetensors` (not recommended).",
49
+ )
50
+ parser.add_argument(
51
+ "--remove_checkpoint_dir",
52
+ action="store_true",
53
+ help="Whether to remove the checkpoint directory after merging.",
54
+ default=False,
55
+ )
56
+
57
+ if subparsers is not None:
58
+ parser.set_defaults(func=merge_command)
59
+ return parser
60
+
61
+
62
+ def main():
63
+ parser = merge_command_parser()
64
+ args = parser.parse_args()
65
+ merge_command(args)
66
+
67
+
68
+ if __name__ == "__main__":
69
+ main()
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/test.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2021 The HuggingFace Team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import argparse
18
+
19
+ from accelerate.test_utils import execute_subprocess_async, path_in_accelerate_package
20
+
21
+
22
+ def test_command_parser(subparsers=None):
23
+ if subparsers is not None:
24
+ parser = subparsers.add_parser("test")
25
+ else:
26
+ parser = argparse.ArgumentParser("Accelerate test command")
27
+
28
+ parser.add_argument(
29
+ "--config_file",
30
+ default=None,
31
+ help=(
32
+ "The path to use to store the config file. Will default to a file named default_config.yaml in the cache "
33
+ "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have "
34
+ "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed "
35
+ "with 'huggingface'."
36
+ ),
37
+ )
38
+
39
+ if subparsers is not None:
40
+ parser.set_defaults(func=test_command)
41
+ return parser
42
+
43
+
44
+ def test_command(args):
45
+ script_name = path_in_accelerate_package("test_utils", "scripts", "test_script.py")
46
+
47
+ if args.config_file is None:
48
+ test_args = [script_name]
49
+ else:
50
+ test_args = f"--config_file={args.config_file} {script_name}".split()
51
+
52
+ cmd = ["accelerate-launch"] + test_args
53
+ result = execute_subprocess_async(cmd)
54
+ if result.returncode == 0:
55
+ print("Test is a success! You are ready for your distributed training!")
56
+
57
+
58
+ def main():
59
+ parser = test_command_parser()
60
+ args = parser.parse_args()
61
+ test_command(args)
62
+
63
+
64
+ if __name__ == "__main__":
65
+ main()
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/to_fsdp2.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2025 The HuggingFace Team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import enum
18
+ import logging
19
+ from pathlib import Path
20
+
21
+ import yaml
22
+
23
+ from accelerate.commands.utils import CustomArgumentParser
24
+
25
+
26
+ class ConversionStatus(enum.Enum):
27
+ NOT_YET_IMPLEMENTED = 0
28
+ REMOVED = -1
29
+
30
+
31
+ ARGUMENT_KEY_MAPPING = {
32
+ # New keys in FSDP2
33
+ "fsdp_version": "fsdp_version",
34
+ "fsdp_reshard_after_forward": "fsdp_reshard_after_forward",
35
+ # https://github.com/pytorch/torchtitan/blob/main/docs/fsdp.md
36
+ # https://huggingface.co/docs/accelerate/en/usage_guides/fsdp
37
+ "fsdp_auto_wrap_policy": "fsdp_auto_wrap_policy",
38
+ "fsdp_backward_prefetch": ConversionStatus.REMOVED,
39
+ "fsdp_forward_prefetch": ConversionStatus.NOT_YET_IMPLEMENTED,
40
+ "fsdp_cpu_ram_efficient_loading": "fsdp_cpu_ram_efficient_loading",
41
+ "fsdp_offload_params": "fsdp_offload_params",
42
+ "fsdp_sharding_strategy": "fsdp_reshard_after_forward",
43
+ "fsdp_state_dict_type": "fsdp_state_dict_type",
44
+ "fsdp_sync_module_states": ConversionStatus.REMOVED,
45
+ "fsdp_transformer_layer_cls_to_wrap": "fsdp_transformer_layer_cls_to_wrap",
46
+ "fsdp_min_num_params": "fsdp_min_num_params",
47
+ "fsdp_use_orig_params": ConversionStatus.REMOVED,
48
+ "fsdp_activation_checkpointing": "fsdp_activation_checkpointing",
49
+ }
50
+
51
+ ARGUMENT_VALUE_MAPPING = {
52
+ "fsdp_sharding_strategy": {
53
+ "FULL_SHARD": True,
54
+ "SHARD_GRAD_OP": False,
55
+ "HYBRID_SHARD": True,
56
+ "HYBRID_SHARD_ZERO2": False,
57
+ "NO_SHARD": False,
58
+ },
59
+ "fsdp_reshard_after_forward": { # Needed to convert newly created configs using FSDP1 to FSDP2
60
+ "FULL_SHARD": True,
61
+ "SHARD_GRAD_OP": False,
62
+ "HYBRID_SHARD": True,
63
+ "HYBRID_SHARD_ZERO2": False,
64
+ "NO_SHARD": False,
65
+ },
66
+ }
67
+
68
+ logger = logging.getLogger(__name__)
69
+
70
+
71
+ def _validate_to_fsdp2_args(args):
72
+ if not Path(args.config_file).exists():
73
+ raise FileNotFoundError(f"Config file {args.config_file} not found")
74
+
75
+ if not args.overwrite and args.output_file is None:
76
+ raise ValueError("If --overwrite is not set, --output_file must be provided")
77
+
78
+ if not args.overwrite and Path(args.output_file).exists():
79
+ raise FileExistsError(f"Output file {args.output_file} already exists and --overwrite is not set")
80
+
81
+
82
+ def convert_config_to_fsdp2(config: dict) -> dict:
83
+ fsdp_config = config.get("fsdp_config", {})
84
+
85
+ if not fsdp_config:
86
+ logger.info("No FSDP config found in the config file, skipping conversion...")
87
+ return config
88
+
89
+ new_fsdp_config = {}
90
+
91
+ if fsdp_config.get("fsdp_version", 1) == 2:
92
+ logger.warning("Config already specfies FSDP2, skipping conversion...")
93
+ logger.warning(
94
+ "If the config doesn't use new argument names, change `fsdp_version` to `1` and rerun the command."
95
+ )
96
+ return config
97
+
98
+ for key, value in fsdp_config.items():
99
+ conversion_status = ARGUMENT_KEY_MAPPING.get(key, None)
100
+ if isinstance(conversion_status, ConversionStatus) or conversion_status is None:
101
+ conversion_status = key
102
+ new_fsdp_config[conversion_status] = value
103
+ continue
104
+
105
+ if conversion_status == ConversionStatus.REMOVED:
106
+ logger.warning(f"Argument {key} has been removed in FSDP2, skipping this key...")
107
+ continue
108
+
109
+ if conversion_status == ConversionStatus.NOT_YET_IMPLEMENTED:
110
+ logger.warning(f"Argument {key} is not yet implemented in FSDP2, skipping this key...")
111
+ continue
112
+
113
+ if conversion_status is None:
114
+ logger.warning(f"Argument {key} is not being converted, skipping this key...")
115
+ new_fsdp_config[key] = value
116
+ else:
117
+ if key in ARGUMENT_VALUE_MAPPING:
118
+ value = ARGUMENT_VALUE_MAPPING[key].get(value, value)
119
+ new_fsdp_config[ARGUMENT_KEY_MAPPING[key]] = value
120
+
121
+ new_fsdp_config["fsdp_version"] = 2
122
+ config["fsdp_config"] = new_fsdp_config
123
+ return config
124
+
125
+
126
+ def to_fsdp2_command_parser(subparsers=None):
127
+ description = "Convert an Accelerate config from FSDP1 to FSDP2"
128
+
129
+ if subparsers is not None:
130
+ parser = subparsers.add_parser("to-fsdp2", description=description)
131
+ else:
132
+ parser = CustomArgumentParser(description=description)
133
+
134
+ parser.add_argument("--config_file", type=str, help="The config file to convert to FSDP2", required=True)
135
+ parser.add_argument(
136
+ "--overwrite",
137
+ action="store_true",
138
+ help="Overwrite the config file if it exists",
139
+ default=False,
140
+ )
141
+ parser.add_argument(
142
+ "--output_file",
143
+ type=str,
144
+ help="The path to the output file to write the converted config to. If not provided, the input file will be overwritten (if --overwrite is set)",
145
+ default=None,
146
+ )
147
+ if subparsers is not None:
148
+ parser.set_defaults(func=to_fsdp2_command)
149
+
150
+ return parser
151
+
152
+
153
+ def load_config(config_file: str) -> dict:
154
+ with open(config_file) as f:
155
+ config = yaml.safe_load(f)
156
+ if not config:
157
+ raise ValueError("Config file is empty")
158
+
159
+ return config
160
+
161
+
162
+ def to_fsdp2_command(args):
163
+ _validate_to_fsdp2_args(args)
164
+ config = load_config(args.config_file)
165
+
166
+ if args.overwrite and args.output_file is None:
167
+ args.output_file = args.config_file
168
+
169
+ new_config = convert_config_to_fsdp2(config)
170
+
171
+ with open(args.output_file, "w") as f:
172
+ yaml.dump(new_config, f)
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/tpu.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import argparse
18
+ import os
19
+ import subprocess
20
+
21
+ from packaging.version import Version, parse
22
+
23
+ from accelerate.commands.config.config_args import default_config_file, load_config_from_file
24
+
25
+
26
+ _description = "Run commands across TPU VMs for initial setup before running `accelerate launch`."
27
+
28
+
29
+ def tpu_command_parser(subparsers=None):
30
+ if subparsers is not None:
31
+ parser = subparsers.add_parser("tpu-config", description=_description)
32
+ else:
33
+ parser = argparse.ArgumentParser("Accelerate tpu-config command", description=_description)
34
+ # Core arguments
35
+ config_args = parser.add_argument_group(
36
+ "Config Arguments", "Arguments that can be configured through `accelerate config`."
37
+ )
38
+ config_args.add_argument(
39
+ "--config_file",
40
+ type=str,
41
+ default=None,
42
+ help="Path to the config file to use for accelerate.",
43
+ )
44
+ config_args.add_argument(
45
+ "--tpu_name",
46
+ default=None,
47
+ help="The name of the TPU to use. If not specified, will use the TPU specified in the config file.",
48
+ )
49
+ config_args.add_argument(
50
+ "--tpu_zone",
51
+ default=None,
52
+ help="The zone of the TPU to use. If not specified, will use the zone specified in the config file.",
53
+ )
54
+ pod_args = parser.add_argument_group("TPU Arguments", "Arguments for options ran inside the TPU.")
55
+ pod_args.add_argument(
56
+ "--use_alpha",
57
+ action="store_true",
58
+ help="Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`.",
59
+ )
60
+ pod_args.add_argument(
61
+ "--command_file",
62
+ default=None,
63
+ help="The path to the file containing the commands to run on the pod on startup.",
64
+ )
65
+ pod_args.add_argument(
66
+ "--command",
67
+ action="append",
68
+ nargs="+",
69
+ help="A command to run on the pod. Can be passed multiple times.",
70
+ )
71
+ pod_args.add_argument(
72
+ "--install_accelerate",
73
+ action="store_true",
74
+ help="Whether to install accelerate on the pod. Defaults to False.",
75
+ )
76
+ pod_args.add_argument(
77
+ "--accelerate_version",
78
+ default="latest",
79
+ help="The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify 'dev' to install from GitHub.",
80
+ )
81
+ pod_args.add_argument(
82
+ "--debug", action="store_true", help="If set, will print the command that would be run instead of running it."
83
+ )
84
+
85
+ if subparsers is not None:
86
+ parser.set_defaults(func=tpu_command_launcher)
87
+ return parser
88
+
89
+
90
+ def tpu_command_launcher(args):
91
+ defaults = None
92
+
93
+ # Get the default from the config file if it exists.
94
+ if args.config_file is not None or os.path.isfile(default_config_file):
95
+ defaults = load_config_from_file(args.config_file)
96
+ if not args.command_file and defaults.command_file is not None and not args.command:
97
+ args.command_file = defaults.command_file
98
+ if not args.command and defaults.commands is not None:
99
+ args.command = defaults.commands
100
+ if not args.tpu_name:
101
+ args.tpu_name = defaults.tpu_name
102
+ if not args.tpu_zone:
103
+ args.tpu_zone = defaults.tpu_zone
104
+ if args.accelerate_version == "dev":
105
+ args.accelerate_version = "git+https://github.com/huggingface/accelerate.git"
106
+ elif args.accelerate_version == "latest":
107
+ args.accelerate_version = "accelerate -U"
108
+ elif isinstance(parse(args.accelerate_version), Version):
109
+ args.accelerate_version = f"accelerate=={args.accelerate_version}"
110
+
111
+ if not args.command_file and not args.command:
112
+ raise ValueError("You must specify either a command file or a command to run on the pod.")
113
+
114
+ if args.command_file:
115
+ with open(args.command_file) as f:
116
+ args.command = [f.read().splitlines()]
117
+
118
+ # To turn list of lists into list of strings
119
+ if isinstance(args.command[0], list):
120
+ args.command = [line for cmd in args.command for line in cmd]
121
+ # Default to the shared folder and install accelerate
122
+ new_cmd = ["cd /usr/share"]
123
+ if args.install_accelerate:
124
+ new_cmd += [f"pip install {args.accelerate_version}"]
125
+ new_cmd += args.command
126
+ args.command = "; ".join(new_cmd)
127
+
128
+ # Then send it to gcloud
129
+ # Eventually try to use google-api-core to do this instead of subprocess
130
+ cmd = ["gcloud"]
131
+ if args.use_alpha:
132
+ cmd += ["alpha"]
133
+ cmd += [
134
+ "compute",
135
+ "tpus",
136
+ "tpu-vm",
137
+ "ssh",
138
+ args.tpu_name,
139
+ "--zone",
140
+ args.tpu_zone,
141
+ "--command",
142
+ args.command,
143
+ "--worker",
144
+ "all",
145
+ ]
146
+ if args.debug:
147
+ print(f"Running {' '.join(cmd)}")
148
+ return
149
+ subprocess.run(cmd)
150
+ print("Successfully setup pod.")
151
+
152
+
153
+ def main():
154
+ parser = tpu_command_parser()
155
+ args = parser.parse_args()
156
+
157
+ tpu_command_launcher(args)
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/commands/utils.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import argparse
16
+
17
+
18
+ class _StoreAction(argparse.Action):
19
+ """
20
+ Custom action that allows for `-` or `_` to be passed in for an argument.
21
+ """
22
+
23
+ def __init__(self, *args, **kwargs):
24
+ super().__init__(*args, **kwargs)
25
+ new_option_strings = []
26
+ for option_string in self.option_strings:
27
+ new_option_strings.append(option_string)
28
+ if "_" in option_string[2:]:
29
+ # Add `-` version to the option string
30
+ new_option_strings.append(option_string.replace("_", "-"))
31
+ self.option_strings = new_option_strings
32
+
33
+ def __call__(self, parser, namespace, values, option_string=None):
34
+ setattr(namespace, self.dest, values)
35
+ if not hasattr(namespace, "nondefault"):
36
+ namespace.nondefault = set()
37
+ namespace.nondefault.add(self.dest)
38
+
39
+
40
+ class _StoreConstAction(_StoreAction):
41
+ """
42
+ Same as `argparse._StoreConstAction` but uses the custom `_StoreAction`.
43
+ """
44
+
45
+ def __init__(self, option_strings, dest, const, default=None, required=False, help=None):
46
+ super().__init__(
47
+ option_strings=option_strings,
48
+ dest=dest,
49
+ nargs=0,
50
+ const=const,
51
+ default=default,
52
+ required=required,
53
+ help=help,
54
+ )
55
+
56
+ def __call__(self, parser, namespace, values, option_string=None):
57
+ super().__call__(parser, namespace, self.const, option_string)
58
+
59
+
60
+ class _StoreTrueAction(_StoreConstAction):
61
+ """
62
+ Same as `argparse._StoreTrueAction` but uses the custom `_StoreConstAction`.
63
+ """
64
+
65
+ def __init__(
66
+ self,
67
+ option_strings,
68
+ dest,
69
+ default=None,
70
+ required=False,
71
+ help=None,
72
+ ):
73
+ super().__init__(
74
+ option_strings=option_strings, dest=dest, const=True, default=default, required=required, help=help
75
+ )
76
+
77
+
78
+ class CustomArgumentGroup(argparse._ArgumentGroup):
79
+ """
80
+ Custom argument group that allows for the use of `-` or `_` in arguments passed and overrides the help for each
81
+ when applicable.
82
+ """
83
+
84
+ def _add_action(self, action):
85
+ args = vars(action)
86
+ if isinstance(action, argparse._StoreTrueAction):
87
+ action = _StoreTrueAction(
88
+ args["option_strings"], args["dest"], args["default"], args["required"], args["help"]
89
+ )
90
+ elif isinstance(action, argparse._StoreConstAction):
91
+ action = _StoreConstAction(
92
+ args["option_strings"],
93
+ args["dest"],
94
+ args["const"],
95
+ args["default"],
96
+ args["required"],
97
+ args["help"],
98
+ )
99
+ elif isinstance(action, argparse._StoreAction):
100
+ action = _StoreAction(**args)
101
+ action = super()._add_action(action)
102
+ return action
103
+
104
+
105
+ class CustomArgumentParser(argparse.ArgumentParser):
106
+ """
107
+ Custom argument parser that allows for the use of `-` or `_` in arguments passed and overrides the help for each
108
+ when applicable.
109
+ """
110
+
111
+ def add_argument(self, *args, **kwargs):
112
+ if "action" in kwargs:
113
+ # Translate action -> class
114
+ if kwargs["action"] == "store_true":
115
+ kwargs["action"] = _StoreTrueAction
116
+ else:
117
+ kwargs["action"] = _StoreAction
118
+ super().add_argument(*args, **kwargs)
119
+
120
+ def add_argument_group(self, *args, **kwargs):
121
+ group = CustomArgumentGroup(self, *args, **kwargs)
122
+ self._action_groups.append(group)
123
+ return group
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/data_loader.py ADDED
@@ -0,0 +1,1451 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import importlib
16
+ import math
17
+ from contextlib import suppress
18
+ from typing import Callable, Optional, Union
19
+
20
+ import torch
21
+ from packaging import version
22
+ from torch.utils.data import BatchSampler, DataLoader, IterableDataset, RandomSampler
23
+
24
+ from .logging import get_logger
25
+ from .state import DistributedType, GradientState, PartialState, is_torch_xla_available
26
+ from .utils import (
27
+ RNGType,
28
+ broadcast,
29
+ broadcast_object_list,
30
+ compare_versions,
31
+ concatenate,
32
+ find_batch_size,
33
+ get_data_structure,
34
+ initialize_tensors,
35
+ is_datasets_available,
36
+ is_torch_version,
37
+ is_torchdata_stateful_dataloader_available,
38
+ send_to_device,
39
+ slice_tensors,
40
+ synchronize_rng_states,
41
+ )
42
+
43
+
44
+ logger = get_logger(__name__)
45
+
46
+ # kwargs of the DataLoader in min version 2.0
47
+ _PYTORCH_DATALOADER_KWARGS = {
48
+ "batch_size": 1,
49
+ "shuffle": False,
50
+ "sampler": None,
51
+ "batch_sampler": None,
52
+ "num_workers": 0,
53
+ "collate_fn": None,
54
+ "pin_memory": False,
55
+ "drop_last": False,
56
+ "timeout": 0,
57
+ "worker_init_fn": None,
58
+ "multiprocessing_context": None,
59
+ "generator": None,
60
+ "prefetch_factor": 2,
61
+ "persistent_workers": False,
62
+ "pin_memory_device": "",
63
+ }
64
+
65
+ # kwargs added after by version
66
+ _PYTORCH_DATALOADER_ADDITIONAL_KWARGS = {"2.6.0": {"in_order": True}}
67
+
68
+ for v, additional_kwargs in _PYTORCH_DATALOADER_ADDITIONAL_KWARGS.items():
69
+ if is_torch_version(">=", v):
70
+ _PYTORCH_DATALOADER_KWARGS.update(additional_kwargs)
71
+
72
+
73
+ class SeedableRandomSampler(RandomSampler):
74
+ """
75
+ Same as a random sampler, except that in `__iter__` a seed can be used.
76
+
77
+ Needed specifically in distributed cases, when the random generator for each GPU needs to start from the same seed
78
+ and be fully reproducable on multiple iterations.
79
+
80
+ If a custom `generator` is passed, it will rely on its initial seed as well as the current iteration it is on
81
+ (stored in `self.epoch`).
82
+ """
83
+
84
+ def __init__(self, *args, **kwargs):
85
+ data_seed = kwargs.pop("data_seed", None)
86
+ super().__init__(*args, **kwargs)
87
+
88
+ self.initial_seed = data_seed if data_seed is not None else torch.random.initial_seed()
89
+ self.epoch = 0
90
+
91
+ def __iter__(self):
92
+ if self.generator is None:
93
+ self.generator = torch.Generator(
94
+ device=torch.get_default_device() if hasattr(torch, "get_default_device") else "cpu"
95
+ )
96
+ self.generator.manual_seed(self.initial_seed)
97
+
98
+ # Allow `self.epoch` to modify the seed of the generator
99
+ seed = self.epoch + self.initial_seed
100
+ # print("Setting seed at epoch", self.epoch, seed)
101
+ self.generator.manual_seed(seed)
102
+ yield from super().__iter__()
103
+ self.set_epoch(self.epoch + 1)
104
+
105
+ def set_epoch(self, epoch: int):
106
+ "Sets the current iteration of the sampler."
107
+ self.epoch = epoch
108
+
109
+
110
+ class BatchSamplerShard(BatchSampler):
111
+ """
112
+ Wraps a PyTorch `BatchSampler` to generate batches for one of the processes only. Instances of this class will
113
+ always yield a number of batches that is a round multiple of `num_processes` and that all have the same size.
114
+ Depending on the value of the `drop_last` attribute of the batch sampler passed, it will either stop the iteration
115
+ at the first batch that would be too small / not present on all processes or loop with indices from the beginning.
116
+
117
+ Args:
118
+ batch_sampler (`torch.utils.data.sampler.BatchSampler`):
119
+ The batch sampler to split in several shards.
120
+ num_processes (`int`, *optional*, defaults to 1):
121
+ The number of processes running concurrently.
122
+ process_index (`int`, *optional*, defaults to 0):
123
+ The index of the current process.
124
+ split_batches (`bool`, *optional*, defaults to `False`):
125
+ Whether the shards should be created by splitting a batch to give a piece of it on each process, or by
126
+ yielding different full batches on each process.
127
+
128
+ On two processes with a sampler of `[[0, 1, 2, 3], [4, 5, 6, 7]]`, this will result in:
129
+
130
+ - the sampler on process 0 to yield `[0, 1, 2, 3]` and the sampler on process 1 to yield `[4, 5, 6, 7]` if
131
+ this argument is set to `False`.
132
+ - the sampler on process 0 to yield `[0, 1]` then `[4, 5]` and the sampler on process 1 to yield `[2, 3]`
133
+ then `[6, 7]` if this argument is set to `True`.
134
+ even_batches (`bool`, *optional*, defaults to `True`):
135
+ Whether or not to loop back at the beginning of the sampler when the number of samples is not a round
136
+ multiple of (original batch size / number of processes).
137
+
138
+ <Tip warning={true}>
139
+
140
+ `BatchSampler`s with varying batch sizes are not enabled by default. To enable this behaviour, set `even_batches`
141
+ equal to `False`
142
+
143
+ </Tip>"""
144
+
145
+ def __init__(
146
+ self,
147
+ batch_sampler: BatchSampler,
148
+ num_processes: int = 1,
149
+ process_index: int = 0,
150
+ split_batches: bool = False,
151
+ even_batches: bool = True,
152
+ ):
153
+ if split_batches and batch_sampler.batch_size % num_processes != 0:
154
+ raise ValueError(
155
+ f"To use `BatchSamplerShard` in `split_batches` mode, the batch size ({batch_sampler.batch_size}) "
156
+ f"needs to be a round multiple of the number of processes ({num_processes})."
157
+ )
158
+ self.batch_sampler = batch_sampler
159
+ self.num_processes = num_processes
160
+ self.process_index = process_index
161
+ self.split_batches = split_batches
162
+ self.even_batches = even_batches
163
+ self.batch_size = getattr(batch_sampler, "batch_size", None)
164
+ self.drop_last = getattr(batch_sampler, "drop_last", False)
165
+ if self.batch_size is None and self.even_batches:
166
+ raise ValueError(
167
+ "You need to use `even_batches=False` when the batch sampler has no batch size. If you "
168
+ "are not calling this method directly, set `accelerator.even_batches=False` instead."
169
+ )
170
+
171
+ @property
172
+ def total_length(self):
173
+ return len(self.batch_sampler)
174
+
175
+ def __len__(self):
176
+ if self.split_batches:
177
+ # Split batches does not change the length of the batch sampler
178
+ return len(self.batch_sampler)
179
+ if len(self.batch_sampler) % self.num_processes == 0:
180
+ # If the length is a round multiple of the number of processes, it's easy.
181
+ return len(self.batch_sampler) // self.num_processes
182
+ length = len(self.batch_sampler) // self.num_processes
183
+ if self.drop_last:
184
+ # Same if we drop the remainder.
185
+ return length
186
+ elif self.even_batches:
187
+ # When we even batches we always get +1
188
+ return length + 1
189
+ else:
190
+ # Otherwise it depends on the process index.
191
+ return length + 1 if self.process_index < len(self.batch_sampler) % self.num_processes else length
192
+
193
+ def __iter__(self):
194
+ return self._iter_with_split() if self.split_batches else self._iter_with_no_split()
195
+
196
+ def _iter_with_split(self):
197
+ initial_data = []
198
+ batch_length = self.batch_sampler.batch_size // self.num_processes
199
+ for idx, batch in enumerate(self.batch_sampler):
200
+ if idx == 0:
201
+ initial_data = batch
202
+ if len(batch) == self.batch_size:
203
+ # If the batch is full, we yield the part of it this process is responsible of.
204
+ yield batch[batch_length * self.process_index : batch_length * (self.process_index + 1)]
205
+
206
+ # If drop_last is True of the last batch was full, iteration is over, otherwise...
207
+ if not self.drop_last and len(initial_data) > 0 and len(batch) < self.batch_size:
208
+ if not self.even_batches:
209
+ if len(batch) > batch_length * self.process_index:
210
+ yield batch[batch_length * self.process_index : batch_length * (self.process_index + 1)]
211
+ else:
212
+ # For degenerate cases where the dataset has less than num_process * batch_size samples
213
+ while len(initial_data) < self.batch_size:
214
+ initial_data += initial_data
215
+ batch = batch + initial_data
216
+ yield batch[batch_length * self.process_index : batch_length * (self.process_index + 1)]
217
+
218
+ def _iter_with_no_split(self):
219
+ initial_data = []
220
+ batch_to_yield = []
221
+ for idx, batch in enumerate(self.batch_sampler):
222
+ # We gather the initial indices in case we need to circle back at the end.
223
+ if not self.drop_last and idx < self.num_processes:
224
+ initial_data += batch
225
+ # We identify the batch to yield but wait until we ar sure every process gets a full batch before actually
226
+ # yielding it.
227
+ if idx % self.num_processes == self.process_index:
228
+ batch_to_yield = batch
229
+ if idx % self.num_processes == self.num_processes - 1 and (
230
+ self.batch_size is None or len(batch) == self.batch_size
231
+ ):
232
+ yield batch_to_yield
233
+ batch_to_yield = []
234
+
235
+ # If drop_last is True, iteration is over, otherwise...
236
+ if not self.drop_last and len(initial_data) > 0:
237
+ if not self.even_batches:
238
+ if len(batch_to_yield) > 0:
239
+ yield batch_to_yield
240
+ else:
241
+ # ... we yield the complete batch we had saved before if it has the proper length
242
+ if len(batch_to_yield) == self.batch_size:
243
+ yield batch_to_yield
244
+
245
+ # For degenerate cases where the dataset has less than num_process * batch_size samples
246
+ while len(initial_data) < self.num_processes * self.batch_size:
247
+ initial_data += initial_data
248
+
249
+ # If the last batch seen was of the proper size, it has been yielded by its process so we move to the next
250
+ if len(batch) == self.batch_size:
251
+ batch = []
252
+ idx += 1
253
+
254
+ # Make sure we yield a multiple of self.num_processes batches
255
+ cycle_index = 0
256
+ while idx % self.num_processes != 0 or len(batch) > 0:
257
+ end_index = cycle_index + self.batch_size - len(batch)
258
+ batch += initial_data[cycle_index:end_index]
259
+ if idx % self.num_processes == self.process_index:
260
+ yield batch
261
+ cycle_index = end_index
262
+ batch = []
263
+ idx += 1
264
+
265
+
266
+ class IterableDatasetShard(IterableDataset):
267
+ """
268
+ Wraps a PyTorch `IterableDataset` to generate samples for one of the processes only. Instances of this class will
269
+ always yield a number of samples that is a round multiple of the actual batch size (depending of the value of
270
+ `split_batches`, this is either `batch_size` or `batch_size x num_processes`). Depending on the value of the
271
+ `drop_last` attribute of the batch sampler passed, it will either stop the iteration at the first batch that would
272
+ be too small or loop with indices from the beginning.
273
+
274
+ Args:
275
+ dataset (`torch.utils.data.dataset.IterableDataset`):
276
+ The batch sampler to split in several shards.
277
+ batch_size (`int`, *optional*, defaults to 1):
278
+ The size of the batches per shard (if `split_batches=False`) or the size of the batches (if
279
+ `split_batches=True`).
280
+ drop_last (`bool`, *optional*, defaults to `False`):
281
+ Whether or not to drop the last incomplete batch or complete the last batches by using the samples from the
282
+ beginning.
283
+ num_processes (`int`, *optional*, defaults to 1):
284
+ The number of processes running concurrently.
285
+ process_index (`int`, *optional*, defaults to 0):
286
+ The index of the current process.
287
+ split_batches (`bool`, *optional*, defaults to `False`):
288
+ Whether the shards should be created by splitting a batch to give a piece of it on each process, or by
289
+ yielding different full batches on each process.
290
+
291
+ On two processes with an iterable dataset yielding of `[0, 1, 2, 3, 4, 5, 6, 7]`, this will result in:
292
+
293
+ - the shard on process 0 to yield `[0, 1, 2, 3]` and the shard on process 1 to yield `[4, 5, 6, 7]` if this
294
+ argument is set to `False`.
295
+ - the shard on process 0 to yield `[0, 1, 4, 5]` and the sampler on process 1 to yield `[2, 3, 6, 7]` if
296
+ this argument is set to `True`.
297
+ """
298
+
299
+ def __init__(
300
+ self,
301
+ dataset: IterableDataset,
302
+ batch_size: int = 1,
303
+ drop_last: bool = False,
304
+ num_processes: int = 1,
305
+ process_index: int = 0,
306
+ split_batches: bool = False,
307
+ ):
308
+ if split_batches and batch_size > 1 and batch_size % num_processes != 0:
309
+ raise ValueError(
310
+ f"To use `IterableDatasetShard` in `split_batches` mode, the batch size ({batch_size}) "
311
+ f"needs to be a round multiple of the number of processes ({num_processes})."
312
+ )
313
+ self.dataset = dataset
314
+ self.batch_size = batch_size
315
+ self.drop_last = drop_last
316
+ self.num_processes = num_processes
317
+ self.process_index = process_index
318
+ self.split_batches = split_batches
319
+
320
+ def set_epoch(self, epoch):
321
+ self.epoch = epoch
322
+ if hasattr(self.dataset, "set_epoch"):
323
+ self.dataset.set_epoch(epoch)
324
+
325
+ def __len__(self):
326
+ # We will just raise the downstream error if the underlying dataset is not sized
327
+ if self.drop_last:
328
+ return (len(self.dataset) // (self.batch_size * self.num_processes)) * self.batch_size
329
+ else:
330
+ return math.ceil(len(self.dataset) / (self.batch_size * self.num_processes)) * self.batch_size
331
+
332
+ def __iter__(self):
333
+ if (
334
+ not hasattr(self.dataset, "set_epoch")
335
+ and hasattr(self.dataset, "generator")
336
+ and isinstance(self.dataset.generator, torch.Generator)
337
+ ):
338
+ self.dataset.generator.manual_seed(self.epoch)
339
+ real_batch_size = self.batch_size if self.split_batches else (self.batch_size * self.num_processes)
340
+ process_batch_size = (self.batch_size // self.num_processes) if self.split_batches else self.batch_size
341
+ process_slice = range(self.process_index * process_batch_size, (self.process_index + 1) * process_batch_size)
342
+
343
+ first_batch = None
344
+ current_batch = []
345
+ for element in self.dataset:
346
+ current_batch.append(element)
347
+ # Wait to have a full batch before yielding elements.
348
+ if len(current_batch) == real_batch_size:
349
+ for i in process_slice:
350
+ yield current_batch[i]
351
+ if first_batch is None:
352
+ first_batch = current_batch.copy()
353
+ current_batch = []
354
+
355
+ # Finished if drop_last is True, otherwise complete the last batch with elements from the beginning.
356
+ if not self.drop_last and len(current_batch) > 0:
357
+ if first_batch is None:
358
+ first_batch = current_batch.copy()
359
+ while len(current_batch) < real_batch_size:
360
+ current_batch += first_batch
361
+ for i in process_slice:
362
+ yield current_batch[i]
363
+
364
+
365
+ class DataLoaderStateMixin:
366
+ """
367
+ Mixin class that adds a state to a `DataLoader` to keep track of the status inside the dataloader such as at the
368
+ end of the iteration, the number of items in the dataset in the last batch relative to the batch size, and other
369
+ useful information that might be needed.
370
+
371
+ **Available attributes:**
372
+
373
+ - **end_of_dataloader** (`bool`) -- Whether at the last iteration or batch
374
+ - **remainder** (`int`) -- The number of items that are remaining in the last batch, relative to the total
375
+ batch size
376
+
377
+ <Tip warning={true}>
378
+
379
+ Inheriters of this class should ensure that the class creates a `GradientState()` instance, stored in
380
+ `self.gradient_state`.
381
+
382
+ </Tip>
383
+
384
+ """
385
+
386
+ def __init_subclass__(cls, **kwargs):
387
+ cls.end_of_dataloader = False
388
+ cls.remainder = -1
389
+
390
+ def reset(self):
391
+ self.end_of_dataloader = False
392
+ self.remainder = -1
393
+
394
+ def begin(self):
395
+ "Prepares the gradient state for the current dataloader"
396
+ self.reset()
397
+ with suppress(Exception):
398
+ if not self._drop_last:
399
+ length = getattr(self.dataset, "total_dataset_length", len(self.dataset))
400
+ self.remainder = length % self.total_batch_size
401
+ self.gradient_state._add_dataloader(self)
402
+
403
+ def end(self):
404
+ "Cleans up the gradient state after exiting the dataloader"
405
+ self.gradient_state._remove_dataloader(self)
406
+
407
+
408
+ class DataLoaderAdapter:
409
+ """
410
+ A class which wraps around a PyTorch `DataLoader` (or variants of it) to be used with the `Accelerator`. For
411
+ compatability reasons, this class inherits from the class it wraps around, so it can be used as a drop-in.
412
+ """
413
+
414
+ def __init__(self, dataset, use_stateful_dataloader=False, batch_sampler=None, **kwargs):
415
+ self.use_stateful_dataloader = use_stateful_dataloader
416
+ if is_torchdata_stateful_dataloader_available():
417
+ from torchdata.stateful_dataloader import StatefulDataLoader
418
+
419
+ if use_stateful_dataloader and not is_torchdata_stateful_dataloader_available():
420
+ raise ImportError(
421
+ "StatefulDataLoader is not available. Please install torchdata version 0.8.0 or higher to use it."
422
+ )
423
+ if use_stateful_dataloader:
424
+ torchdata_version = version.parse(importlib.metadata.version("torchdata"))
425
+ if (
426
+ "in_order" in kwargs
427
+ and compare_versions(torchdata_version, "<", "0.11")
428
+ and is_torch_version(">=", "2.6.0")
429
+ ):
430
+ kwargs.pop("in_order")
431
+ self.base_dataloader = StatefulDataLoader(dataset, batch_sampler=batch_sampler, **kwargs)
432
+ else:
433
+ self.base_dataloader = DataLoader(dataset, batch_sampler=batch_sampler, **kwargs)
434
+
435
+ if hasattr(self.base_dataloader, "state_dict"):
436
+ self.dl_state_dict = self.base_dataloader.state_dict()
437
+
438
+ def __getattr__(self, name):
439
+ # Avoid infinite recursion if we try to access a nonexistent base_dataloader attribute.
440
+ if name == "base_dataloader":
441
+ raise AttributeError()
442
+ # Delegate attribute access to the internal dataloader
443
+ return getattr(self.base_dataloader, name)
444
+
445
+ def state_dict(self):
446
+ return self.dl_state_dict
447
+
448
+ def load_state_dict(self, state_dict):
449
+ self.base_dataloader.load_state_dict(state_dict)
450
+
451
+ @property
452
+ def __class__(self):
453
+ """
454
+ In order to maintain backwards compatability with other code, we need to ensure `isinstance(obj, DataLoader)`
455
+ returs true. This is because some downstream code assumes that the `DataLoader` is the base class of the
456
+ object.
457
+ """
458
+ return self.base_dataloader.__class__
459
+
460
+ def __len__(self):
461
+ return len(self.base_dataloader)
462
+
463
+ def adjust_state_dict_for_prefetch(self):
464
+ """
465
+ Adjusts the state dict for prefetching. Natively, this will adjust all of the iters yielded keys in
466
+ `self.dl_state_dict` by a factor of `num_processes - 1`, however if a custom correction is needed, this can be
467
+ overridden.
468
+
469
+ This should modify `self.dl_state_dict` directly
470
+ """
471
+ # The state dict will be off by a factor of `n-1` batch too many during DDP,
472
+ # so we need to adjust it here
473
+ if PartialState().distributed_type != DistributedType.NO:
474
+ factor = PartialState().num_processes - 1
475
+ if self.dl_state_dict["_sampler_iter_yielded"] > 0:
476
+ self.dl_state_dict["_sampler_iter_yielded"] -= factor
477
+ if self.dl_state_dict["_num_yielded"] > 0:
478
+ self.dl_state_dict["_num_yielded"] -= factor
479
+ if self.dl_state_dict["_index_sampler_state"] is not None:
480
+ if (
481
+ "samples_yielded" in self.dl_state_dict["_index_sampler_state"]
482
+ and self.dl_state_dict["_index_sampler_state"]["samples_yielded"] > 0
483
+ ):
484
+ self.dl_state_dict["_index_sampler_state"]["samples_yielded"] -= self.batch_size * factor
485
+
486
+ def _update_state_dict(self):
487
+ # The state_dict of the underlying base_dataloader may be ahead of what is currently being yielded.
488
+ # E.g. the implementation of DataLoaderShard involves having an underlying iterator 1 element ahead of
489
+ # what it wants to yield.
490
+ #
491
+ # _update_state_dict is called to snapshot the state_dict that would properly recover the DataLoaderAdapter.
492
+ if hasattr(self.base_dataloader, "state_dict"):
493
+ self.dl_state_dict = self.base_dataloader.state_dict()
494
+ # Potentially modify the state_dict to adjust for prefetching
495
+ self.adjust_state_dict_for_prefetch()
496
+ # Then tag if we are at the end of the dataloader
497
+ self.dl_state_dict["_iterator_finished"] = self.end_of_dataloader
498
+
499
+
500
+ class DataLoaderShard(DataLoaderAdapter, DataLoaderStateMixin):
501
+ """
502
+ Subclass of `DataLoaderAdapter` that will deal with device placement and current distributed setup.
503
+
504
+ Args:
505
+ dataset (`torch.utils.data.dataset.Dataset`):
506
+ The dataset to use to build this dataloader.
507
+ device (`torch.device`, *optional*):
508
+ If passed, the device to put all batches on.
509
+ rng_types (list of `str` or [`~utils.RNGType`]):
510
+ The list of random number generators to synchronize at the beginning of each iteration. Should be one or
511
+ several of:
512
+
513
+ - `"torch"`: the base torch random number generator
514
+ - `"cuda"`: the CUDA random number generator (GPU only)
515
+ - `"xla"`: the XLA random number generator (TPU only)
516
+ - `"generator"`: an optional `torch.Generator`
517
+ synchronized_generator (`torch.Generator`, *optional*):
518
+ A random number generator to keep synchronized across processes.
519
+ skip_batches (`int`, *optional*, defaults to 0):
520
+ The number of batches to skip at the beginning.
521
+ use_stateful_dataloader (`bool`, *optional*, defaults to `False`):
522
+ Whether to have this class adapt `StatefulDataLoader` from `torchdata` instead of the regular `DataLoader`.
523
+ **kwargs (additional keyword arguments, *optional*):
524
+ All other keyword arguments to pass to the regular `DataLoader` initialization.
525
+
526
+ **Available attributes:**
527
+
528
+ - **total_batch_size** (`int`) -- Total batch size of the dataloader across all processes.
529
+ Equal to the original batch size when `split_batches=True`; otherwise the original batch size * the total
530
+ number of processes
531
+
532
+ - **total_dataset_length** (`int`) -- Total length of the inner dataset across all processes.
533
+ """
534
+
535
+ def __init__(
536
+ self,
537
+ dataset,
538
+ device=None,
539
+ rng_types=None,
540
+ synchronized_generator=None,
541
+ skip_batches=0,
542
+ use_stateful_dataloader=False,
543
+ _drop_last: bool = False,
544
+ _non_blocking: bool = False,
545
+ torch_device_mesh=None,
546
+ **kwargs,
547
+ ):
548
+ super().__init__(dataset, use_stateful_dataloader=use_stateful_dataloader, **kwargs)
549
+ self.device = device
550
+ self.rng_types = rng_types
551
+ self.synchronized_generator = synchronized_generator
552
+ self.skip_batches = skip_batches
553
+ self.gradient_state = GradientState()
554
+ self._drop_last = _drop_last
555
+ self._non_blocking = _non_blocking
556
+ self.iteration = 0
557
+
558
+ def __iter__(self):
559
+ if self.rng_types is not None:
560
+ synchronize_rng_states(self.rng_types, self.synchronized_generator)
561
+ self.begin()
562
+
563
+ self.set_epoch(self.iteration)
564
+ dataloader_iter = self.base_dataloader.__iter__()
565
+ # We iterate one batch ahead to check when we are at the end
566
+ try:
567
+ current_batch = next(dataloader_iter)
568
+ except StopIteration:
569
+ self.end()
570
+ return
571
+
572
+ batch_index = 0
573
+ while True:
574
+ try:
575
+ # But we still move it to the device so it is done before `StopIteration` is reached
576
+ if self.device is not None:
577
+ current_batch = send_to_device(current_batch, self.device, non_blocking=self._non_blocking)
578
+ self._update_state_dict()
579
+ next_batch = next(dataloader_iter)
580
+ if batch_index >= self.skip_batches:
581
+ yield current_batch
582
+ batch_index += 1
583
+ current_batch = next_batch
584
+ except StopIteration:
585
+ self.end_of_dataloader = True
586
+ self._update_state_dict()
587
+ if batch_index >= self.skip_batches:
588
+ yield current_batch
589
+ break
590
+
591
+ self.iteration += 1
592
+ self.end()
593
+
594
+ def __reduce__(self):
595
+ """
596
+ Define the `__reduce__` method to ensure a `DataLoaderShard` can be pickled and unpickled. This needs to be
597
+ explicitly defined since default pickling behavior is broken by `DataLoaderAdapter` messing with its
598
+ `__class__` member.
599
+ """
600
+ args = super().__reduce__()
601
+ return (DataLoaderShard, *args[1:])
602
+
603
+ def set_epoch(self, epoch: int):
604
+ # In case it is manually passed in, the user can set it to what they like
605
+ if self.iteration != epoch:
606
+ self.iteration = epoch
607
+ if hasattr(self.batch_sampler, "set_epoch"):
608
+ self.batch_sampler.set_epoch(epoch)
609
+ if hasattr(self.batch_sampler, "sampler") and hasattr(self.batch_sampler.sampler, "set_epoch"):
610
+ self.batch_sampler.sampler.set_epoch(epoch)
611
+ if (
612
+ hasattr(self.batch_sampler, "batch_sampler")
613
+ and hasattr(self.batch_sampler.batch_sampler, "sampler")
614
+ and hasattr(self.batch_sampler.batch_sampler.sampler, "set_epoch")
615
+ ):
616
+ self.batch_sampler.batch_sampler.sampler.set_epoch(epoch)
617
+ # We support if a custom `Dataset` implementation has `set_epoch`
618
+ # or in general HF datasets `Datasets`
619
+ elif hasattr(self.dataset, "set_epoch"):
620
+ self.dataset.set_epoch(epoch)
621
+
622
+ @property
623
+ def total_batch_size(self):
624
+ batch_sampler = self.sampler if isinstance(self.sampler, BatchSampler) else self.batch_sampler
625
+ return (
626
+ batch_sampler.batch_size
627
+ if getattr(batch_sampler, "split_batches", False)
628
+ else (batch_sampler.batch_size * getattr(batch_sampler, "num_processes", 1))
629
+ )
630
+
631
+ @property
632
+ def total_dataset_length(self):
633
+ if hasattr(self.dataset, "total_length"):
634
+ return self.dataset.total_length
635
+ else:
636
+ return len(self.dataset)
637
+
638
+ def get_sampler(self):
639
+ return get_sampler(self)
640
+
641
+ def set_sampler(self, sampler):
642
+ sampler_is_batch_sampler = isinstance(self.sampler, BatchSampler)
643
+ if sampler_is_batch_sampler:
644
+ self.sampler.sampler = sampler
645
+ else:
646
+ self.batch_sampler.sampler = sampler
647
+ if hasattr(self.batch_sampler, "batch_sampler"):
648
+ self.batch_sampler.batch_sampler.sampler = sampler
649
+
650
+
651
+ if is_torch_xla_available():
652
+ import torch_xla.distributed.parallel_loader as xpl
653
+
654
+ class MpDeviceLoaderWrapper(xpl.MpDeviceLoader):
655
+ """
656
+ Wrapper for the xpl.MpDeviceLoader class that knows the total batch size.
657
+
658
+ XLA preloading threads will all call DataLoaderShard's __iter__(). Remove rng_types from DataLoaderShard to
659
+ prevent it from using the XLA device in the preloading threads, and synchronize the RNG once from the main
660
+ thread only.
661
+
662
+ **Available attributes:**
663
+
664
+ - **total_batch_size** (`int`) -- Total batch size of the dataloader across all processes.
665
+ Equal to the original batch size when `split_batches=True`; otherwise the original batch size * the total
666
+ number of processes
667
+
668
+ - **total_dataset_length** (`int`) -- Total length of the inner dataset across all processes.
669
+ """
670
+
671
+ def __init__(self, dataloader: DataLoaderShard, device: torch.device):
672
+ super().__init__(dataloader, device)
673
+ self._rng_types = self._loader.rng_types
674
+ self._loader.rng_types = None
675
+ self.device = device
676
+
677
+ def __iter__(self):
678
+ if self._rng_types is not None:
679
+ synchronize_rng_states(self._rng_types, self._loader.synchronized_generator)
680
+
681
+ return super().__iter__()
682
+
683
+ def set_epoch(self, epoch: int):
684
+ if hasattr(self.dataloader, "set_epoch"):
685
+ self.dataloader.set_epoch(epoch)
686
+
687
+ @property
688
+ def total_batch_size(self):
689
+ return self._loader.total_batch_size
690
+
691
+ @property
692
+ def total_dataset_length(self):
693
+ return self._loader.total_dataset_length
694
+
695
+ @property
696
+ def batch_sampler(self):
697
+ return self._loader.batch_sampler
698
+
699
+ @property
700
+ def dataloader(self):
701
+ return self._loader
702
+
703
+
704
+ class DataLoaderDispatcher(DataLoaderAdapter, DataLoaderStateMixin):
705
+ """
706
+ Subclass of `DataLoaderAdapter` that will iterate and preprocess on process 0 only, then dispatch on each process
707
+ their part of the batch.
708
+
709
+ Args:
710
+ split_batches (`bool`, *optional*, defaults to `False`):
711
+ Whether the resulting `DataLoader` should split the batches of the original data loader across devices or
712
+ yield full batches (in which case it will yield batches starting at the `process_index`-th and advancing of
713
+ `num_processes` batches at each iteration). Another way to see this is that the observed batch size will be
714
+ the same as the initial `dataloader` if this option is set to `True`, the batch size of the initial
715
+ `dataloader` multiplied by `num_processes` otherwise. Setting this option to `True` requires that the batch
716
+ size of the `dataloader` is a round multiple of `batch_size`.
717
+ skip_batches (`int`, *optional*, defaults to 0):
718
+ The number of batches to skip at the beginning of an iteration.
719
+ use_stateful_dataloader (`bool`, *optional*, defaults to `False`):
720
+ Whether to have this class adapt `StatefulDataLoader` from `torchdata` instead of the regular `DataLoader`.
721
+
722
+ **Available attributes:**
723
+
724
+ - **total_batch_size** (`int`) -- Total batch size of the dataloader across all processes.
725
+ Equal to the original batch size when `split_batches=True`; otherwise the original batch size * the total
726
+ number of processes
727
+
728
+ - **total_dataset_length** (`int`) -- Total length of the inner dataset across all processes.
729
+ """
730
+
731
+ def __init__(
732
+ self,
733
+ dataset,
734
+ split_batches: bool = False,
735
+ skip_batches=0,
736
+ use_stateful_dataloader=False,
737
+ _drop_last: bool = False,
738
+ _non_blocking: bool = False,
739
+ slice_fn=None,
740
+ torch_device_mesh=None,
741
+ **kwargs,
742
+ ):
743
+ shuffle = False
744
+ from torch.utils.data.datapipes.iter.combinatorics import ShufflerIterDataPipe
745
+
746
+ # We need to save the shuffling state of the DataPipe
747
+ if isinstance(dataset, ShufflerIterDataPipe):
748
+ shuffle = dataset._shuffle_enabled
749
+ super().__init__(dataset, use_stateful_dataloader=use_stateful_dataloader, **kwargs)
750
+ self.split_batches = split_batches
751
+ if shuffle:
752
+ torch.utils.data.graph_settings.apply_shuffle_settings(dataset, shuffle=shuffle)
753
+
754
+ self.gradient_state = GradientState()
755
+ self.state = PartialState()
756
+ self._drop_last = _drop_last
757
+ self._non_blocking = _non_blocking
758
+ self.skip_batches = skip_batches
759
+ self.torch_device_mesh = torch_device_mesh
760
+
761
+ self.slice_fn = slice_tensors if slice_fn is None else slice_fn
762
+ self.iteration = 0
763
+
764
+ # if a device mesh is provided extract each dimension (dp, fsdp, tp)
765
+ # device mesh may hold any number of dimensions, however,
766
+ # below code is for targetted support for dp, fsdp and tp
767
+
768
+ # device mesh will be used only if there is tp involved
769
+ # or any multi-dimensional parallelism involving tp
770
+ # (dp, tp) (fsdp, tp) (dp, fsdp, tp)
771
+ # otherwise the default behavour not using device mesh should be sufficient
772
+ # since multi dimensional parallelism devoid of tp would anyway need
773
+ # different batches for each process irrespective of dp or fsdp
774
+ self.submesh_tp = None
775
+ self.submesh_dp = None
776
+ self.submesh_fsdp = None
777
+ if self.torch_device_mesh and "tp" in self.torch_device_mesh.mesh_dim_names:
778
+ self.submesh_tp = self.torch_device_mesh["tp"]
779
+ if "dp" in self.torch_device_mesh.mesh_dim_names:
780
+ self.submesh_dp = self.torch_device_mesh["dp"]
781
+ if "fsdp" in self.torch_device_mesh.mesh_dim_names:
782
+ self.submesh_fsdp = self.torch_device_mesh["fsdp"]
783
+ if self.submesh_tp and (self.submesh_dp or self.submesh_fsdp):
784
+ raise ValueError("TP + (DP/FSDP) is not yet supported in dispatch mode")
785
+
786
+ def _fetch_batches(self, iterator):
787
+ batches, batch = None, None
788
+ # On process 0, we gather the batch to dispatch.
789
+ if self.state.process_index == 0:
790
+ # Procedure to support TP only is simpler
791
+ # since we want to dispatch the same batch of samples across all ranks
792
+ # this removes complexity of handling multiple tp rank groups when TP + DP
793
+ # combination is involved.
794
+
795
+ try:
796
+ # for TP case avoid using split_batches
797
+ # since it would mean that the dataloader should be spilling out
798
+ # duplicates of batches.
799
+ if self.split_batches:
800
+ # One batch of the main iterator is dispatched and split.
801
+ if self.submesh_tp:
802
+ logger.warning(
803
+ "Use of split_batches for TP would need the dataloader to produce duplicate batches,"
804
+ "otherwise, use dispatch_batches=True instead."
805
+ )
806
+ self._update_state_dict()
807
+ batch = next(iterator)
808
+ else:
809
+ # num_processes batches of the main iterator are concatenated then dispatched and split.
810
+ # We add the batches one by one so we have the remainder available when drop_last=False.
811
+ batches = []
812
+ if self.submesh_tp:
813
+ # when tp, extract single batch and then replicate
814
+ self._update_state_dict()
815
+ batch = next(iterator)
816
+ batches = [batch] * self.state.num_processes
817
+ else:
818
+ for _ in range(self.state.num_processes):
819
+ self._update_state_dict()
820
+ batches.append(next(iterator))
821
+ try:
822
+ batch = concatenate(batches, dim=0)
823
+ except RuntimeError as e:
824
+ raise RuntimeError(
825
+ "You can't use batches of different size with `dispatch_batches=True` or when using an `IterableDataset`."
826
+ "either pass `dispatch_batches=False` and have each process fetch its own batch "
827
+ " or pass `split_batches=True`. By doing so, the main process will fetch a full batch and "
828
+ "slice it into `num_processes` batches for each process."
829
+ ) from e
830
+ # In both cases, we need to get the structure of the batch that we will broadcast on other
831
+ # processes to initialize the tensors with the right shape.
832
+ # data_structure, stop_iteration
833
+ batch_info = [get_data_structure(batch), False]
834
+ except StopIteration:
835
+ batch_info = [None, True]
836
+ else:
837
+ batch_info = [None, self._stop_iteration]
838
+ # This is inplace, so after this instruction, every process has the same `batch_info` as process 0.
839
+ broadcast_object_list(batch_info)
840
+ self._stop_iteration = batch_info[1]
841
+ if self._stop_iteration:
842
+ # If drop_last is False and split_batches is False, we may have a remainder to take care of.
843
+ if not self.split_batches and not self._drop_last:
844
+ if self.state.process_index == 0 and len(batches) > 0:
845
+ batch = concatenate(batches, dim=0)
846
+ batch_info = [get_data_structure(batch), False]
847
+ else:
848
+ batch_info = [None, True]
849
+ broadcast_object_list(batch_info)
850
+ return batch, batch_info
851
+
852
+ def __iter__(self):
853
+ self.begin()
854
+ self.set_epoch(self.iteration)
855
+ main_iterator = None
856
+ if is_torch_version(">=", "2.0.1"):
857
+ # NOTE PyTorch DataLoader adds forward compatibilities for DataPipes, which broadcasts
858
+ # shared seed to all dist processes. Thus, we need to create iterator for all dist processes.
859
+ # But, we only iterate through the DataLoader on process 0.
860
+ main_iterator = self.base_dataloader.__iter__()
861
+ elif self.state.process_index == 0:
862
+ main_iterator = self.base_dataloader.__iter__()
863
+ stop_iteration = False
864
+ self._stop_iteration = False
865
+ first_batch = None
866
+ next_batch, next_batch_info = self._fetch_batches(main_iterator)
867
+ batch_index = 0
868
+ while not stop_iteration:
869
+ batch, batch_info = next_batch, next_batch_info
870
+
871
+ if self.state.process_index != 0:
872
+ # Initialize tensors on other processes than process 0.
873
+ batch = initialize_tensors(batch_info[0])
874
+ batch = send_to_device(batch, self.state.device, non_blocking=self._non_blocking)
875
+ # Broadcast the batch before splitting it.
876
+ batch = broadcast(batch, from_process=0)
877
+
878
+ if not self._drop_last and first_batch is None:
879
+ # We keep at least num processes elements of the first batch to be able to complete the last batch
880
+ first_batch = self.slice_fn(
881
+ batch,
882
+ slice(0, self.state.num_processes),
883
+ process_index=self.state.process_index,
884
+ num_processes=self.state.num_processes,
885
+ )
886
+
887
+ if batch is None:
888
+ raise ValueError(
889
+ f"Batch does not contain any data (`{batch}`). At the end of all iterable data available before expected stop iteration."
890
+ )
891
+
892
+ observed_batch_size = find_batch_size(batch)
893
+ batch_size = observed_batch_size // self.state.num_processes
894
+
895
+ stop_iteration = self._stop_iteration
896
+ if not stop_iteration:
897
+ # We may still be at the end of the dataloader without knowing it yet: if there is nothing left in
898
+ # the dataloader since the number of batches is a round multiple of the number of processes.
899
+ next_batch, next_batch_info = self._fetch_batches(main_iterator)
900
+ # next_batch_info[0] is None when there are no more batches, otherwise we still need to process them.
901
+ if self._stop_iteration and next_batch_info[0] is None:
902
+ stop_iteration = True
903
+
904
+ if not self._drop_last and stop_iteration and observed_batch_size % self.state.num_processes != 0:
905
+ # If the last batch is not complete, let's add the first batch to it.
906
+ batch = concatenate([batch, first_batch], dim=0)
907
+ # Batch size computation above is wrong, it's off by 1 so we fix it.
908
+ batch_size += 1
909
+
910
+ data_slice = slice(self.state.process_index * batch_size, (self.state.process_index + 1) * batch_size)
911
+ batch = self.slice_fn(
912
+ batch,
913
+ data_slice,
914
+ process_index=self.state.process_index,
915
+ num_processes=self.state.num_processes,
916
+ )
917
+
918
+ if stop_iteration:
919
+ self.end_of_dataloader = True
920
+ self._update_state_dict()
921
+ self.remainder = observed_batch_size
922
+ if batch_index >= self.skip_batches:
923
+ yield batch
924
+ batch_index += 1
925
+ self.iteration += 1
926
+ self.end()
927
+
928
+ def set_epoch(self, epoch: int):
929
+ # In case it is manually passed in, the user can set it to what they like
930
+ if self.iteration != epoch:
931
+ self.iteration = epoch
932
+ if hasattr(self.batch_sampler, "sampler") and hasattr(self.batch_sampler.sampler, "set_epoch"):
933
+ self.batch_sampler.sampler.set_epoch(epoch)
934
+ elif hasattr(self.dataset, "set_epoch"):
935
+ self.dataset.set_epoch(epoch)
936
+
937
+ def __len__(self):
938
+ whole_length = len(self.base_dataloader)
939
+ if self.split_batches:
940
+ return whole_length
941
+ elif self._drop_last:
942
+ return whole_length // self.state.num_processes
943
+ else:
944
+ return math.ceil(whole_length / self.state.num_processes)
945
+
946
+ def __reduce__(self):
947
+ """
948
+ Define the `__reduce__` method to ensure a `DataLoaderDispatcher` can be pickled and unpickled. This needs to
949
+ be explicitly defined since default pickling behavior is broken by `DataLoaderAdapter` messing with its
950
+ `__class__` member.
951
+ """
952
+ args = super().__reduce__()
953
+ return (DataLoaderDispatcher, *args[1:])
954
+
955
+ @property
956
+ def total_batch_size(self):
957
+ return (
958
+ self.dataset.batch_size if self.split_batches else (self.dataset.batch_size * self.dataset.num_processes)
959
+ )
960
+
961
+ @property
962
+ def total_dataset_length(self):
963
+ return len(self.dataset)
964
+
965
+ def get_sampler(self):
966
+ return get_sampler(self)
967
+
968
+ def set_sampler(self, sampler):
969
+ sampler_is_batch_sampler = isinstance(self.sampler, BatchSampler)
970
+ if sampler_is_batch_sampler:
971
+ self.sampler.sampler = sampler
972
+ else:
973
+ self.batch_sampler.sampler = sampler
974
+ if hasattr(self.batch_sampler, "batch_sampler"):
975
+ self.batch_sampler.batch_sampler.sampler = sampler
976
+
977
+
978
+ def get_sampler(dataloader):
979
+ """
980
+ Get the sampler associated to the dataloader
981
+
982
+ Args:
983
+ dataloader (`torch.utils.data.dataloader.DataLoader`):
984
+ The data loader to split across several devices.
985
+ Returns:
986
+ `torch.utils.data.Sampler`: The sampler associated to the dataloader
987
+ """
988
+ sampler_is_batch_sampler = isinstance(dataloader.sampler, BatchSampler)
989
+ if sampler_is_batch_sampler:
990
+ sampler = getattr(dataloader.sampler, "sampler", None)
991
+ else:
992
+ sampler = getattr(dataloader.batch_sampler, "sampler", None)
993
+ return sampler
994
+
995
+
996
+ def prepare_data_loader(
997
+ dataloader: DataLoader,
998
+ device: Optional[torch.device] = None,
999
+ num_processes: Optional[int] = None,
1000
+ process_index: Optional[int] = None,
1001
+ split_batches: bool = False,
1002
+ put_on_device: bool = False,
1003
+ rng_types: Optional[list[Union[str, RNGType]]] = None,
1004
+ dispatch_batches: Optional[bool] = None,
1005
+ even_batches: bool = True,
1006
+ slice_fn_for_dispatch: Optional[Callable] = None,
1007
+ use_seedable_sampler: bool = False,
1008
+ data_seed: Optional[int] = None,
1009
+ non_blocking: bool = False,
1010
+ use_stateful_dataloader: bool = False,
1011
+ torch_device_mesh=None,
1012
+ ) -> DataLoader:
1013
+ """
1014
+ Wraps a PyTorch `DataLoader` to generate batches for one of the processes only.
1015
+
1016
+ Depending on the value of the `drop_last` attribute of the `dataloader` passed, it will either stop the iteration
1017
+ at the first batch that would be too small / not present on all processes or loop with indices from the beginning.
1018
+
1019
+ Args:
1020
+ dataloader (`torch.utils.data.dataloader.DataLoader`):
1021
+ The data loader to split across several devices.
1022
+ device (`torch.device`):
1023
+ The target device for the returned `DataLoader`.
1024
+ num_processes (`int`, *optional*):
1025
+ The number of processes running concurrently. Will default to the value given by [`~state.PartialState`].
1026
+ process_index (`int`, *optional*):
1027
+ The index of the current process. Will default to the value given by [`~state.PartialState`].
1028
+ split_batches (`bool`, *optional*, defaults to `False`):
1029
+ Whether the resulting `DataLoader` should split the batches of the original data loader across devices or
1030
+ yield full batches (in which case it will yield batches starting at the `process_index`-th and advancing of
1031
+ `num_processes` batches at each iteration).
1032
+
1033
+ Another way to see this is that the observed batch size will be the same as the initial `dataloader` if
1034
+ this option is set to `True`, the batch size of the initial `dataloader` multiplied by `num_processes`
1035
+ otherwise.
1036
+
1037
+ Setting this option to `True` requires that the batch size of the `dataloader` is a round multiple of
1038
+ `batch_size`.
1039
+ put_on_device (`bool`, *optional*, defaults to `False`):
1040
+ Whether or not to put the batches on `device` (only works if the batches are nested list, tuples or
1041
+ dictionaries of tensors).
1042
+ rng_types (list of `str` or [`~utils.RNGType`]):
1043
+ The list of random number generators to synchronize at the beginning of each iteration. Should be one or
1044
+ several of:
1045
+
1046
+ - `"torch"`: the base torch random number generator
1047
+ - `"cuda"`: the CUDA random number generator (GPU only)
1048
+ - `"xla"`: the XLA random number generator (TPU only)
1049
+ - `"generator"`: the `torch.Generator` of the sampler (or batch sampler if there is no sampler in your
1050
+ dataloader) or of the iterable dataset (if it exists) if the underlying dataset is of that type.
1051
+
1052
+ dispatch_batches (`bool`, *optional*):
1053
+ If set to `True`, the dataloader prepared is only iterated through on the main process and then the batches
1054
+ are split and broadcast to each process. Will default to `True` when the underlying dataset is an
1055
+ `IterableDataset`, `False` otherwise.
1056
+ even_batches (`bool`, *optional*, defaults to `True`):
1057
+ If set to `True`, in cases where the total batch size across all processes does not exactly divide the
1058
+ dataset, samples at the start of the dataset will be duplicated so the batch can be divided equally among
1059
+ all workers.
1060
+ slice_fn_for_dispatch (`Callable`, *optional*`):
1061
+ If passed, this function will be used to slice tensors across `num_processes`. Will default to
1062
+ [`~utils.slice_tensors`]. This argument is used only when `dispatch_batches` is set to `True` and will be
1063
+ ignored otherwise.
1064
+ use_seedable_sampler (`bool`, *optional*, defaults to `False`):
1065
+ Whether to use the [`~data_loader.SeedableRandomSampler`] instead of a `RandomSampler` for better
1066
+ reproducability. Comes at a cost of potentially different performances due to different shuffling
1067
+ algorithms but ensures results will be the *exact* same. Should be paired with `set_seed()` at every
1068
+ `self.set_epoch`
1069
+ data_seed (`int`, *optional*, defaults to `None`):
1070
+ The seed to use for the underlying generator when using `use_seedable_sampler`. If `None`, the generator
1071
+ will use the current default seed from torch.
1072
+ non_blocking (`bool`, *optional*, defaults to `False`):
1073
+ If set to `True`, dataloader will utilize non-blocking host-to-device transfers. If the dataloader has
1074
+ `pin_memory` set to `True`, this will help to increase overlap between data transfer and computations.
1075
+ use_stateful_dataloader (`bool`, *optional*, defaults to `False`):
1076
+ "If set to true, the dataloader prepared by the Accelerator will be backed by "
1077
+ "[torchdata.StatefulDataLoader](https://github.com/pytorch/data/tree/main/torchdata/stateful_dataloader).
1078
+ This requires `torchdata` version 0.8.0 or higher that supports StatefulDataLoader to be installed."
1079
+ torch_device_mesh (`torch.distributed.DeviceMesh`, *optional*, defaults to `None`):
1080
+ PyTorch device mesh.
1081
+
1082
+
1083
+ Returns:
1084
+ `torch.utils.data.dataloader.DataLoader`: A new data loader that will yield the portion of the batches
1085
+
1086
+ <Tip warning={true}>
1087
+
1088
+ `BatchSampler`s with varying batch sizes are not enabled by default. To enable this behaviour, set `even_batches`
1089
+ equal to `False`
1090
+
1091
+ </Tip>
1092
+ """
1093
+ if dispatch_batches is None:
1094
+ if not put_on_device:
1095
+ dispatch_batches = False
1096
+ else:
1097
+ dispatch_batches = isinstance(dataloader.dataset, IterableDataset)
1098
+
1099
+ if dispatch_batches and not put_on_device:
1100
+ raise ValueError("Using `dispatch_batches=True` requires `put_on_device=True`.")
1101
+ # Grab defaults from PartialState
1102
+ state = PartialState()
1103
+ if num_processes is None:
1104
+ num_processes = state.num_processes
1105
+
1106
+ if process_index is None:
1107
+ process_index = state.process_index
1108
+
1109
+ if torch_device_mesh:
1110
+ if state.distributed_type == DistributedType.DEEPSPEED:
1111
+ # In DeepSpeed, the optimizer sharing level in DP is determined by the config file.
1112
+ # Only considers "dp" and "tp".
1113
+ # Given a device mesh (dp, tp) = (2, 3):
1114
+ # - From the data parallel perspective, ranks should be structured as: 0 0 0 1 1 1
1115
+ # - Processes with the same DP rank will receive the same batch.
1116
+ submesh_tp_size = 1
1117
+ if "tp" in torch_device_mesh.mesh_dim_names:
1118
+ submesh_tp_size = torch_device_mesh["tp"].size()
1119
+ process_index = process_index // submesh_tp_size
1120
+ num_processes = num_processes // submesh_tp_size
1121
+ else:
1122
+ # when device mesh is used, specifically with TP
1123
+ # then there is need to update process_index and num_processes
1124
+ # to bring in the effect of generating same batch across TP ranks
1125
+ # and different batch across FSDP and DP ranks.
1126
+ # Example:
1127
+ # if device mesh is (dp,fsdp,tp) = (2, 2, 3)
1128
+ # ranks would range from 0...11
1129
+ # from data angle ranks should look like 0 0 0 1 1 1 2 2 2 3 3 3
1130
+ # processes with same ranks/ids would receive the same batch
1131
+ # for CP the same as TP applies
1132
+ submesh_fsdp_size = 1
1133
+ submesh_dp_size = 1
1134
+ submesh_tp_size = 1
1135
+ submesh_cp_size = 1
1136
+ if "tp" in torch_device_mesh.mesh_dim_names:
1137
+ submesh_tp_size = torch_device_mesh["tp"].size()
1138
+ if "cp" in torch_device_mesh.mesh_dim_names:
1139
+ submesh_cp_size = torch_device_mesh["cp"].size()
1140
+ if "dp_replicate" in torch_device_mesh.mesh_dim_names:
1141
+ submesh_dp_size = torch_device_mesh["dp_replicate"].size()
1142
+ if "dp_shard" in torch_device_mesh.mesh_dim_names:
1143
+ submesh_fsdp_size = torch_device_mesh["dp_shard"].size()
1144
+ process_index = process_index // (submesh_tp_size * submesh_cp_size)
1145
+ num_processes = submesh_fsdp_size * submesh_dp_size
1146
+
1147
+ # Sanity check
1148
+ if split_batches:
1149
+ if dataloader.batch_size is not None:
1150
+ batch_size_for_check = dataloader.batch_size
1151
+ else:
1152
+ # For custom batch_sampler
1153
+ if hasattr(dataloader.batch_sampler, "batch_size"):
1154
+ batch_size_for_check = dataloader.batch_sampler.batch_size
1155
+ else:
1156
+ raise ValueError(
1157
+ "In order to use `split_batches==True` you must have a `batch_size` attribute either in the passed "
1158
+ "`dataloader` or `dataloader.batch_sampler` objects, and it has to return a natural number. "
1159
+ "Your `dataloader.batch_size` is None and `dataloader.batch_sampler` "
1160
+ f"(`{type(dataloader.batch_sampler)}`) does not have the `batch_size` attribute set."
1161
+ )
1162
+
1163
+ if batch_size_for_check > 1 and batch_size_for_check % num_processes != 0:
1164
+ raise ValueError(
1165
+ f"To use a `DataLoader` in `split_batches` mode, the batch size ({dataloader.batch_size}) "
1166
+ f"needs to be a round multiple of the number of processes ({num_processes})."
1167
+ )
1168
+
1169
+ new_dataset = dataloader.dataset
1170
+ # Iterable dataset doesn't like batch_sampler, but data_loader creates a default one for it
1171
+ new_batch_sampler = dataloader.batch_sampler if not isinstance(new_dataset, IterableDataset) else None
1172
+ sampler_is_batch_sampler = isinstance(dataloader.sampler, BatchSampler)
1173
+ synchronized_generator = None
1174
+
1175
+ sampler = get_sampler(dataloader)
1176
+ if isinstance(sampler, RandomSampler) and use_seedable_sampler:
1177
+ # When iterating through the dataloader during distributed processes
1178
+ # we want to ensure that on each process we are iterating through the same
1179
+ # samples in the same order if a seed is set. This requires a tweak
1180
+ # to the `torch.utils.data.RandomSampler` class (if used).
1181
+ sampler = SeedableRandomSampler(
1182
+ data_source=sampler.data_source,
1183
+ replacement=sampler.replacement,
1184
+ num_samples=sampler._num_samples,
1185
+ generator=getattr(
1186
+ sampler,
1187
+ "generator",
1188
+ torch.Generator(device=torch.get_default_device() if hasattr(torch, "get_default_device") else "cpu"),
1189
+ ),
1190
+ data_seed=data_seed,
1191
+ )
1192
+
1193
+ if isinstance(dataloader.sampler, RandomSampler) and state.distributed_type == DistributedType.XLA:
1194
+ # isinstance(dataloader.sampler, RandomSampler) indicates the original dataloader has `shuffle` enabled.
1195
+ generator = torch.Generator(
1196
+ device=torch.get_default_device() if hasattr(torch, "get_default_device") else "cpu"
1197
+ )
1198
+ seed = int(torch.empty((), dtype=torch.int64).random_().item())
1199
+ generator.manual_seed(seed)
1200
+ dataloader.generator = generator
1201
+ dataloader.sampler.generator = generator
1202
+ # No change if no multiprocess
1203
+ if (num_processes != 1 or state.distributed_type == DistributedType.MEGATRON_LM) and not dispatch_batches:
1204
+ if is_datasets_available():
1205
+ from datasets import IterableDataset as DatasetsIterableDataset
1206
+ if (
1207
+ is_datasets_available()
1208
+ and isinstance(new_dataset, DatasetsIterableDataset)
1209
+ and not split_batches
1210
+ and new_dataset.n_shards > num_processes
1211
+ ):
1212
+ new_dataset = new_dataset.shard(num_shards=num_processes, index=process_index)
1213
+ elif isinstance(new_dataset, IterableDataset):
1214
+ if getattr(dataloader.dataset, "generator", None) is not None:
1215
+ synchronized_generator = dataloader.dataset.generator
1216
+ new_dataset = IterableDatasetShard(
1217
+ new_dataset,
1218
+ batch_size=dataloader.batch_size,
1219
+ drop_last=dataloader.drop_last,
1220
+ num_processes=num_processes,
1221
+ process_index=process_index,
1222
+ split_batches=split_batches,
1223
+ )
1224
+ else:
1225
+ if not use_seedable_sampler and hasattr(sampler, "generator"):
1226
+ if sampler.generator is None:
1227
+ sampler.generator = torch.Generator(
1228
+ device=torch.get_default_device() if hasattr(torch, "get_default_device") else "cpu"
1229
+ )
1230
+ seed = int(torch.empty((), dtype=torch.int64).random_().item())
1231
+ sampler.generator.manual_seed(seed)
1232
+ synchronized_generator = sampler.generator
1233
+ batch_sampler = dataloader.sampler if sampler_is_batch_sampler else dataloader.batch_sampler
1234
+ new_batch_sampler = BatchSamplerShard(
1235
+ batch_sampler,
1236
+ num_processes=num_processes,
1237
+ process_index=process_index,
1238
+ split_batches=split_batches,
1239
+ even_batches=even_batches,
1240
+ )
1241
+
1242
+ # We ignore all of those since they are all dealt with by our new_batch_sampler
1243
+ ignore_kwargs = [
1244
+ "batch_size",
1245
+ "shuffle",
1246
+ "sampler",
1247
+ "batch_sampler",
1248
+ "drop_last",
1249
+ ]
1250
+
1251
+ if rng_types is not None and synchronized_generator is None and "generator" in rng_types:
1252
+ rng_types.remove("generator")
1253
+
1254
+ kwargs = {
1255
+ k: getattr(dataloader, k, _PYTORCH_DATALOADER_KWARGS[k])
1256
+ for k in _PYTORCH_DATALOADER_KWARGS
1257
+ if k not in ignore_kwargs
1258
+ }
1259
+
1260
+ # Need to provide batch_size as batch_sampler is None for Iterable dataset
1261
+ if new_batch_sampler is None:
1262
+ kwargs["drop_last"] = dataloader.drop_last
1263
+ kwargs["batch_size"] = (
1264
+ dataloader.batch_size // num_processes if split_batches and not dispatch_batches else dataloader.batch_size
1265
+ )
1266
+ if dispatch_batches:
1267
+ kwargs.pop("generator")
1268
+ dataloader = DataLoaderDispatcher(
1269
+ new_dataset,
1270
+ split_batches=split_batches,
1271
+ batch_sampler=new_batch_sampler,
1272
+ _drop_last=dataloader.drop_last,
1273
+ _non_blocking=non_blocking,
1274
+ slice_fn=slice_fn_for_dispatch,
1275
+ use_stateful_dataloader=use_stateful_dataloader,
1276
+ torch_device_mesh=torch_device_mesh,
1277
+ **kwargs,
1278
+ )
1279
+ elif sampler_is_batch_sampler:
1280
+ dataloader = DataLoaderShard(
1281
+ new_dataset,
1282
+ device=device if put_on_device and state.distributed_type != DistributedType.XLA else None,
1283
+ sampler=new_batch_sampler,
1284
+ batch_size=dataloader.batch_size,
1285
+ rng_types=rng_types,
1286
+ _drop_last=dataloader.drop_last,
1287
+ _non_blocking=non_blocking,
1288
+ synchronized_generator=synchronized_generator,
1289
+ use_stateful_dataloader=use_stateful_dataloader,
1290
+ **kwargs,
1291
+ )
1292
+ else:
1293
+ dataloader = DataLoaderShard(
1294
+ new_dataset,
1295
+ device=device if put_on_device and state.distributed_type != DistributedType.XLA else None,
1296
+ batch_sampler=new_batch_sampler,
1297
+ rng_types=rng_types,
1298
+ synchronized_generator=synchronized_generator,
1299
+ _drop_last=dataloader.drop_last,
1300
+ _non_blocking=non_blocking,
1301
+ use_stateful_dataloader=use_stateful_dataloader,
1302
+ **kwargs,
1303
+ )
1304
+
1305
+ if isinstance(sampler, SeedableRandomSampler) and use_seedable_sampler:
1306
+ dataloader.set_sampler(sampler)
1307
+ if state.distributed_type == DistributedType.XLA:
1308
+ return MpDeviceLoaderWrapper(dataloader, device)
1309
+ return dataloader
1310
+
1311
+
1312
+ class SkipBatchSampler(BatchSampler):
1313
+ """
1314
+ A `torch.utils.data.BatchSampler` that skips the first `n` batches of another `torch.utils.data.BatchSampler`.
1315
+ Should not be used if the original dataloader is a `StatefulDataLoader`.
1316
+ """
1317
+
1318
+ def __init__(self, batch_sampler, skip_batches=0):
1319
+ self.batch_sampler = batch_sampler
1320
+ self.skip_batches = skip_batches
1321
+
1322
+ def __iter__(self):
1323
+ for index, samples in enumerate(self.batch_sampler):
1324
+ if index >= self.skip_batches:
1325
+ yield samples
1326
+
1327
+ @property
1328
+ def total_length(self):
1329
+ return len(self.batch_sampler)
1330
+
1331
+ def __len__(self):
1332
+ return len(self.batch_sampler) - self.skip_batches
1333
+
1334
+
1335
+ class SkipDataLoader(DataLoaderAdapter, DataLoaderStateMixin):
1336
+ """
1337
+ Subclass of a PyTorch `DataLoader` that will skip the first batches. Generally it's preferable to use
1338
+ `skip_first_batches`/`torchdata.StatefulDataLoader` instead of this class.
1339
+
1340
+ Args:
1341
+ dataset (`torch.utils.data.dataset.Dataset`):
1342
+ The dataset to use to build this dataloader.
1343
+ skip_batches (`int`, *optional*, defaults to 0):
1344
+ The number of batches to skip at the beginning.
1345
+ kwargs:
1346
+ All other keyword arguments to pass to the regular `DataLoader` initialization.
1347
+ """
1348
+
1349
+ def __init__(self, dataset, skip_batches=0, use_stateful_dataloader=False, **kwargs):
1350
+ super().__init__(dataset, use_stateful_dataloader=use_stateful_dataloader, **kwargs)
1351
+ self.skip_batches = skip_batches
1352
+ self.gradient_state = GradientState()
1353
+
1354
+ def __iter__(self):
1355
+ self.begin()
1356
+ for index, batch in enumerate(self.base_dataloader.__iter__()):
1357
+ if index >= self.skip_batches:
1358
+ self._update_state_dict()
1359
+ yield batch
1360
+ self.end()
1361
+
1362
+ def __len__(self):
1363
+ return len(self.base_dataloader) - self.skip_batches
1364
+
1365
+ def __reduce__(self):
1366
+ """
1367
+ Define the `__reduce__` method to ensure a `SkipDataLoader` can be pickled and unpickled. This needs to be
1368
+ explicitly defined since default pickling behavior is broken by `DataLoaderAdapter` messing with its
1369
+ `__class__` member.
1370
+ """
1371
+ args = super().__reduce__()
1372
+ return (SkipDataLoader, *args[1:])
1373
+
1374
+
1375
+ def skip_first_batches(dataloader, num_batches=0):
1376
+ """
1377
+ Creates a `torch.utils.data.DataLoader` that will efficiently skip the first `num_batches`. Should not be used if
1378
+ the original dataloader is a `StatefulDataLoader`.
1379
+ """
1380
+ state = PartialState()
1381
+ if state.distributed_type == DistributedType.XLA:
1382
+ device = dataloader.device
1383
+ dataloader = dataloader.dataloader
1384
+
1385
+ dataset = dataloader.dataset
1386
+ sampler_is_batch_sampler = False
1387
+ if isinstance(dataset, IterableDataset):
1388
+ new_batch_sampler = None
1389
+ else:
1390
+ sampler_is_batch_sampler = isinstance(dataloader.sampler, BatchSampler)
1391
+ batch_sampler = dataloader.sampler if sampler_is_batch_sampler else dataloader.batch_sampler
1392
+ new_batch_sampler = SkipBatchSampler(batch_sampler, skip_batches=num_batches)
1393
+
1394
+ # We ignore all of those since they are all dealt with by our new_batch_sampler
1395
+ ignore_kwargs = [
1396
+ "batch_size",
1397
+ "shuffle",
1398
+ "sampler",
1399
+ "batch_sampler",
1400
+ "drop_last",
1401
+ ]
1402
+
1403
+ kwargs = {
1404
+ k: getattr(dataloader, k, _PYTORCH_DATALOADER_KWARGS[k])
1405
+ for k in _PYTORCH_DATALOADER_KWARGS
1406
+ if k not in ignore_kwargs
1407
+ }
1408
+
1409
+ # Need to provide batch_size as batch_sampler is None for Iterable dataset
1410
+ if new_batch_sampler is None:
1411
+ kwargs["drop_last"] = dataloader.drop_last
1412
+ kwargs["batch_size"] = dataloader.batch_size
1413
+
1414
+ if isinstance(dataloader, DataLoaderDispatcher):
1415
+ if new_batch_sampler is None:
1416
+ # Need to manually skip batches in the dataloader
1417
+ kwargs["skip_batches"] = num_batches
1418
+ dataloader = DataLoaderDispatcher(
1419
+ dataset,
1420
+ split_batches=dataloader.split_batches,
1421
+ batch_sampler=new_batch_sampler,
1422
+ _drop_last=dataloader._drop_last,
1423
+ **kwargs,
1424
+ )
1425
+ elif isinstance(dataloader, DataLoaderShard):
1426
+ if new_batch_sampler is None:
1427
+ # Need to manually skip batches in the dataloader
1428
+ kwargs["skip_batches"] = num_batches
1429
+ elif sampler_is_batch_sampler:
1430
+ kwargs["sampler"] = new_batch_sampler
1431
+ kwargs["batch_size"] = dataloader.batch_size
1432
+ else:
1433
+ kwargs["batch_sampler"] = new_batch_sampler
1434
+ dataloader = DataLoaderShard(
1435
+ dataset,
1436
+ device=dataloader.device,
1437
+ rng_types=dataloader.rng_types,
1438
+ synchronized_generator=dataloader.synchronized_generator,
1439
+ **kwargs,
1440
+ )
1441
+ else:
1442
+ if new_batch_sampler is None:
1443
+ # Need to manually skip batches in the dataloader
1444
+ dataloader = SkipDataLoader(dataset, skip_batches=num_batches, **kwargs)
1445
+ else:
1446
+ dataloader = DataLoader(dataset, batch_sampler=new_batch_sampler, **kwargs)
1447
+
1448
+ if state.distributed_type == DistributedType.XLA:
1449
+ dataloader = MpDeviceLoaderWrapper(dataloader, device)
1450
+
1451
+ return dataloader
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/hooks.py ADDED
@@ -0,0 +1,765 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import functools
16
+ from collections.abc import Mapping
17
+ from typing import Optional, Union
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+
22
+ from .state import PartialState
23
+ from .utils import (
24
+ PrefixedDataset,
25
+ find_device,
26
+ named_module_tensors,
27
+ send_to_device,
28
+ set_module_tensor_to_device,
29
+ )
30
+ from .utils.imports import (
31
+ is_mlu_available,
32
+ is_musa_available,
33
+ is_npu_available,
34
+ )
35
+ from .utils.memory import clear_device_cache
36
+ from .utils.modeling import get_non_persistent_buffers
37
+ from .utils.other import recursive_getattr
38
+
39
+
40
+ _accelerate_added_attributes = ["to", "cuda", "npu", "xpu", "mlu", "sdaa", "musa"]
41
+
42
+
43
+ class ModelHook:
44
+ """
45
+ A hook that contains callbacks to be executed just before and after the forward method of a model. The difference
46
+ with PyTorch existing hooks is that they get passed along the kwargs.
47
+
48
+ Class attribute:
49
+ - **no_grad** (`bool`, *optional*, defaults to `False`) -- Whether or not to execute the actual forward pass under
50
+ the `torch.no_grad()` context manager.
51
+ """
52
+
53
+ no_grad = False
54
+
55
+ def init_hook(self, module):
56
+ """
57
+ To be executed when the hook is attached to the module.
58
+
59
+ Args:
60
+ module (`torch.nn.Module`): The module attached to this hook.
61
+ """
62
+ return module
63
+
64
+ def pre_forward(self, module, *args, **kwargs):
65
+ """
66
+ To be executed just before the forward method of the model.
67
+
68
+ Args:
69
+ module (`torch.nn.Module`): The module whose forward pass will be executed just after this event.
70
+ args (`Tuple[Any]`): The positional arguments passed to the module.
71
+ kwargs (`Dict[Str, Any]`): The keyword arguments passed to the module.
72
+
73
+ Returns:
74
+ `Tuple[Tuple[Any], Dict[Str, Any]]`: A tuple with the treated `args` and `kwargs`.
75
+ """
76
+ return args, kwargs
77
+
78
+ def post_forward(self, module, output):
79
+ """
80
+ To be executed just after the forward method of the model.
81
+
82
+ Args:
83
+ module (`torch.nn.Module`): The module whose forward pass been executed just before this event.
84
+ output (`Any`): The output of the module.
85
+
86
+ Returns:
87
+ `Any`: The processed `output`.
88
+ """
89
+ return output
90
+
91
+ def detach_hook(self, module):
92
+ """
93
+ To be executed when the hook is detached from a module.
94
+
95
+ Args:
96
+ module (`torch.nn.Module`): The module detached from this hook.
97
+ """
98
+ return module
99
+
100
+
101
+ class SequentialHook(ModelHook):
102
+ """
103
+ A hook that can contain several hooks and iterates through them at each event.
104
+ """
105
+
106
+ def __init__(self, *hooks):
107
+ self.hooks = hooks
108
+
109
+ def init_hook(self, module):
110
+ for hook in self.hooks:
111
+ module = hook.init_hook(module)
112
+ return module
113
+
114
+ def pre_forward(self, module, *args, **kwargs):
115
+ for hook in self.hooks:
116
+ args, kwargs = hook.pre_forward(module, *args, **kwargs)
117
+ return args, kwargs
118
+
119
+ def post_forward(self, module, output):
120
+ for hook in self.hooks:
121
+ output = hook.post_forward(module, output)
122
+ return output
123
+
124
+ def detach_hook(self, module):
125
+ for hook in self.hooks:
126
+ module = hook.detach_hook(module)
127
+ return module
128
+
129
+
130
+ def add_hook_to_module(module: nn.Module, hook: ModelHook, append: bool = False):
131
+ """
132
+ Adds a hook to a given module. This will rewrite the `forward` method of the module to include the hook, to remove
133
+ this behavior and restore the original `forward` method, use `remove_hook_from_module`.
134
+
135
+ <Tip warning={true}>
136
+
137
+ If the module already contains a hook, this will replace it with the new hook passed by default. To chain two hooks
138
+ together, pass `append=True`, so it chains the current and new hook into an instance of the `SequentialHook` class.
139
+
140
+ </Tip>
141
+
142
+ Args:
143
+ module (`torch.nn.Module`):
144
+ The module to attach a hook to.
145
+ hook (`ModelHook`):
146
+ The hook to attach.
147
+ append (`bool`, *optional*, defaults to `False`):
148
+ Whether the hook should be chained with an existing one (if module already contains a hook) or not.
149
+
150
+ Returns:
151
+ `torch.nn.Module`: The same module, with the hook attached (the module is modified in place, so the result can
152
+ be discarded).
153
+ """
154
+ if append and (getattr(module, "_hf_hook", None) is not None):
155
+ old_hook = module._hf_hook
156
+ remove_hook_from_module(module)
157
+ hook = SequentialHook(old_hook, hook)
158
+
159
+ if hasattr(module, "_hf_hook") and hasattr(module, "_old_forward"):
160
+ # If we already put some hook on this module, we replace it with the new one.
161
+ old_forward = module._old_forward
162
+ else:
163
+ old_forward = module.forward
164
+ module._old_forward = old_forward
165
+
166
+ module = hook.init_hook(module)
167
+ module._hf_hook = hook
168
+
169
+ def new_forward(module, *args, **kwargs):
170
+ args, kwargs = module._hf_hook.pre_forward(module, *args, **kwargs)
171
+ if module._hf_hook.no_grad:
172
+ with torch.no_grad():
173
+ output = module._old_forward(*args, **kwargs)
174
+ else:
175
+ output = module._old_forward(*args, **kwargs)
176
+ return module._hf_hook.post_forward(module, output)
177
+
178
+ # Overriding a GraphModuleImpl forward freezes the forward call and later modifications on the graph will fail.
179
+ # Reference: https://pytorch.slack.com/archives/C3PDTEV8E/p1705929610405409
180
+ if "GraphModuleImpl" in str(type(module)):
181
+ module.__class__.forward = functools.update_wrapper(functools.partial(new_forward, module), old_forward)
182
+ else:
183
+ module.forward = functools.update_wrapper(functools.partial(new_forward, module), old_forward)
184
+
185
+ return module
186
+
187
+
188
+ def remove_hook_from_module(module: nn.Module, recurse=False):
189
+ """
190
+ Removes any hook attached to a module via `add_hook_to_module`.
191
+
192
+ Args:
193
+ module (`torch.nn.Module`): The module to attach a hook to.
194
+ recurse (`bool`, **optional**): Whether to remove the hooks recursively
195
+
196
+ Returns:
197
+ `torch.nn.Module`: The same module, with the hook detached (the module is modified in place, so the result can
198
+ be discarded).
199
+ """
200
+
201
+ if hasattr(module, "_hf_hook"):
202
+ module._hf_hook.detach_hook(module)
203
+ delattr(module, "_hf_hook")
204
+
205
+ if hasattr(module, "_old_forward"):
206
+ # Overriding a GraphModuleImpl forward freezes the forward call and later modifications on the graph will fail.
207
+ # Reference: https://pytorch.slack.com/archives/C3PDTEV8E/p1705929610405409
208
+ if "GraphModuleImpl" in str(type(module)):
209
+ module.__class__.forward = module._old_forward
210
+ else:
211
+ module.forward = module._old_forward
212
+ delattr(module, "_old_forward")
213
+
214
+ # Remove accelerate added warning hooks from dispatch_model
215
+ for attr in _accelerate_added_attributes:
216
+ module.__dict__.pop(attr, None)
217
+
218
+ if recurse:
219
+ for child in module.children():
220
+ remove_hook_from_module(child, recurse)
221
+
222
+ return module
223
+
224
+
225
+ class AlignDevicesHook(ModelHook):
226
+ """
227
+ A generic `ModelHook` that ensures inputs and model weights are on the same device for the forward pass of the
228
+ associated module, potentially offloading the weights after the forward pass.
229
+
230
+ Args:
231
+ execution_device (`torch.device`, *optional*):
232
+ The device on which inputs and model weights should be placed before the forward pass.
233
+ offload (`bool`, *optional*, defaults to `False`):
234
+ Whether or not the weights should be offloaded after the forward pass.
235
+ io_same_device (`bool`, *optional*, defaults to `False`):
236
+ Whether or not the output should be placed on the same device as the input was.
237
+ weights_map (`Mapping[str, torch.Tensor]`, *optional*):
238
+ When the model weights are offloaded, a (potentially lazy) map from param names to the tensor values.
239
+ offload_buffers (`bool`, *optional*, defaults to `False`):
240
+ Whether or not to include the associated module's buffers when offloading.
241
+ place_submodules (`bool`, *optional*, defaults to `False`):
242
+ Whether to place the submodules on `execution_device` during the `init_hook` event.
243
+ """
244
+
245
+ def __init__(
246
+ self,
247
+ execution_device: Optional[Union[int, str, torch.device]] = None,
248
+ offload: bool = False,
249
+ io_same_device: bool = False,
250
+ weights_map: Optional[Mapping] = None,
251
+ offload_buffers: bool = False,
252
+ place_submodules: bool = False,
253
+ skip_keys: Optional[Union[str, list[str]]] = None,
254
+ tied_params_map: Optional[dict[int, dict[torch.device, torch.Tensor]]] = None,
255
+ ):
256
+ self.execution_device = execution_device
257
+ self.offload = offload
258
+ self.io_same_device = io_same_device
259
+ self.weights_map = weights_map
260
+ self.offload_buffers = offload_buffers
261
+ self.place_submodules = place_submodules
262
+ self.skip_keys = skip_keys
263
+
264
+ # Will contain the input device when `io_same_device=True`.
265
+ self.input_device = None
266
+ self.param_original_devices = {}
267
+ self.buffer_original_devices = {}
268
+ self.tied_params_names = set()
269
+
270
+ # The hook pre_forward/post_forward need to have knowledge of this dictionary, as with offloading we want to avoid duplicating memory
271
+ # for tied weights already loaded on the target execution device.
272
+ self.tied_params_map = tied_params_map
273
+
274
+ def __repr__(self):
275
+ return (
276
+ f"AlignDevicesHook(execution_device={self.execution_device}, offload={self.offload}, "
277
+ f"io_same_device={self.io_same_device}, offload_buffers={self.offload_buffers}, "
278
+ f"place_submodules={self.place_submodules}, skip_keys={repr(self.skip_keys)})"
279
+ )
280
+
281
+ def init_hook(self, module):
282
+ # In case the AlignDevicesHook is on meta device, ignore tied weights as data_ptr() is then always zero.
283
+ if self.execution_device == "meta" or self.execution_device == torch.device("meta"):
284
+ self.tied_params_map = None
285
+
286
+ if not self.offload and self.execution_device is not None:
287
+ for name, _ in named_module_tensors(module, recurse=self.place_submodules):
288
+ set_module_tensor_to_device(module, name, self.execution_device, tied_params_map=self.tied_params_map)
289
+ elif self.offload:
290
+ self.original_devices = {
291
+ name: param.device for name, param in named_module_tensors(module, recurse=self.place_submodules)
292
+ }
293
+ if self.weights_map is None:
294
+ self.weights_map = {
295
+ name: param.to("cpu")
296
+ for name, param in named_module_tensors(
297
+ module, include_buffers=self.offload_buffers, recurse=self.place_submodules
298
+ )
299
+ }
300
+ for name, _ in named_module_tensors(
301
+ module, include_buffers=self.offload_buffers, recurse=self.place_submodules, remove_non_persistent=True
302
+ ):
303
+ # When using disk offloading, we can not rely on `weights_map[name].data_ptr()` as the reference pointer,
304
+ # as we have no guarantee that safetensors' `file.get_tensor()` will always give the same pointer.
305
+ # As we have no reliable way to track the shared data pointer of tied weights in this case, we use tied_params_names: List[str]
306
+ # to add on the fly pointers to `tied_params_map` in the pre_forward call.
307
+ if (
308
+ self.tied_params_map is not None
309
+ and recursive_getattr(module, name).data_ptr() in self.tied_params_map
310
+ ):
311
+ self.tied_params_names.add(name)
312
+
313
+ set_module_tensor_to_device(module, name, "meta")
314
+
315
+ if not self.offload_buffers and self.execution_device is not None:
316
+ for name, _ in module.named_buffers(recurse=self.place_submodules):
317
+ set_module_tensor_to_device(
318
+ module, name, self.execution_device, tied_params_map=self.tied_params_map
319
+ )
320
+ elif self.offload_buffers and self.execution_device is not None:
321
+ for name in get_non_persistent_buffers(module, recurse=self.place_submodules):
322
+ set_module_tensor_to_device(
323
+ module, name, self.execution_device, tied_params_map=self.tied_params_map
324
+ )
325
+
326
+ return module
327
+
328
+ def pre_forward(self, module, *args, **kwargs):
329
+ if self.io_same_device:
330
+ self.input_device = find_device([args, kwargs])
331
+ if self.offload:
332
+ self.tied_pointers_to_remove = set()
333
+
334
+ for name, _ in named_module_tensors(
335
+ module,
336
+ include_buffers=self.offload_buffers,
337
+ recurse=self.place_submodules,
338
+ remove_non_persistent=True,
339
+ ):
340
+ fp16_statistics = None
341
+ value = self.weights_map[name]
342
+ if "weight" in name and name.replace("weight", "SCB") in self.weights_map.keys():
343
+ if value.dtype == torch.int8:
344
+ fp16_statistics = self.weights_map[name.replace("weight", "SCB")]
345
+
346
+ # In case we are using offloading with tied weights, we need to keep track of the offloaded weights
347
+ # that are loaded on device at this point, as we will need to remove them as well from the dictionary
348
+ # self.tied_params_map in order to allow to free memory.
349
+ if name in self.tied_params_names and value.data_ptr() not in self.tied_params_map:
350
+ self.tied_params_map[value.data_ptr()] = {}
351
+
352
+ if (
353
+ value is not None
354
+ and self.tied_params_map is not None
355
+ and value.data_ptr() in self.tied_params_map
356
+ and self.execution_device not in self.tied_params_map[value.data_ptr()]
357
+ ):
358
+ self.tied_pointers_to_remove.add((value.data_ptr(), self.execution_device))
359
+
360
+ set_module_tensor_to_device(
361
+ module,
362
+ name,
363
+ self.execution_device,
364
+ value=value,
365
+ fp16_statistics=fp16_statistics,
366
+ tied_params_map=self.tied_params_map,
367
+ )
368
+
369
+ return send_to_device(args, self.execution_device), send_to_device(
370
+ kwargs, self.execution_device, skip_keys=self.skip_keys
371
+ )
372
+
373
+ def post_forward(self, module, output):
374
+ if self.offload:
375
+ for name, _ in named_module_tensors(
376
+ module,
377
+ include_buffers=self.offload_buffers,
378
+ recurse=self.place_submodules,
379
+ remove_non_persistent=True,
380
+ ):
381
+ set_module_tensor_to_device(module, name, "meta")
382
+ if type(module).__name__ == "Linear8bitLt":
383
+ module.state.SCB = None
384
+ module.state.CxB = None
385
+
386
+ # We may have loaded tied weights into self.tied_params_map (avoiding to load them several times in e.g. submodules): remove them from
387
+ # this dictionary to allow the garbage collector to do its job.
388
+ for value_pointer, device in self.tied_pointers_to_remove:
389
+ if isinstance(device, int):
390
+ if is_npu_available():
391
+ device = f"npu:{device}"
392
+ elif is_mlu_available():
393
+ device = f"mlu:{device}"
394
+ elif is_musa_available():
395
+ device = f"musa:{device}"
396
+ if device in self.tied_params_map[value_pointer]:
397
+ del self.tied_params_map[value_pointer][device]
398
+ self.tied_pointers_to_remove = set()
399
+ if self.io_same_device and self.input_device is not None:
400
+ output = send_to_device(output, self.input_device, skip_keys=self.skip_keys)
401
+
402
+ return output
403
+
404
+ def detach_hook(self, module):
405
+ if self.offload:
406
+ for name, device in self.original_devices.items():
407
+ if device != torch.device("meta"):
408
+ set_module_tensor_to_device(module, name, device, value=self.weights_map.get(name, None))
409
+ return module
410
+
411
+
412
+ def attach_execution_device_hook(
413
+ module: torch.nn.Module,
414
+ execution_device: Union[int, str, torch.device],
415
+ skip_keys: Optional[Union[str, list[str]]] = None,
416
+ preload_module_classes: Optional[list[str]] = None,
417
+ tied_params_map: Optional[dict[int, dict[torch.device, torch.Tensor]]] = None,
418
+ ):
419
+ """
420
+ Recursively attaches `AlignDevicesHook` to all submodules of a given model to make sure they have the right
421
+ execution device
422
+
423
+ Args:
424
+ module (`torch.nn.Module`):
425
+ The module where we want to attach the hooks.
426
+ execution_device (`int`, `str` or `torch.device`):
427
+ The device on which inputs and model weights should be placed before the forward pass.
428
+ skip_keys (`str` or `List[str]`, *optional*):
429
+ A list of keys to ignore when moving inputs or outputs between devices.
430
+ preload_module_classes (`List[str]`, *optional*):
431
+ A list of classes whose instances should load all their weights (even in the submodules) at the beginning
432
+ of the forward. This should only be used for classes that have submodules which are registered but not
433
+ called directly during the forward, for instance if a `dense` linear layer is registered, but at forward,
434
+ `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly.
435
+ tied_params_map (Optional[Dict[int, Dict[torch.device, torch.Tensor]]], *optional*, defaults to `None`):
436
+ A map of data pointers to dictionaries of devices to already dispatched tied weights. For a given execution
437
+ device, this parameter is useful to reuse the first available pointer of a shared weight for all others,
438
+ instead of duplicating memory.
439
+ """
440
+ if not hasattr(module, "_hf_hook") and len(module.state_dict()) > 0:
441
+ add_hook_to_module(
442
+ module,
443
+ AlignDevicesHook(execution_device, skip_keys=skip_keys, tied_params_map=tied_params_map),
444
+ )
445
+
446
+ # Break the recursion if we get to a preload module.
447
+ if preload_module_classes is not None and module.__class__.__name__ in preload_module_classes:
448
+ return
449
+
450
+ for child in module.children():
451
+ attach_execution_device_hook(
452
+ child,
453
+ execution_device,
454
+ skip_keys=skip_keys,
455
+ preload_module_classes=preload_module_classes,
456
+ tied_params_map=tied_params_map,
457
+ )
458
+
459
+
460
+ def attach_align_device_hook(
461
+ module: torch.nn.Module,
462
+ execution_device: Optional[torch.device] = None,
463
+ offload: bool = False,
464
+ weights_map: Optional[Mapping] = None,
465
+ offload_buffers: bool = False,
466
+ module_name: str = "",
467
+ skip_keys: Optional[Union[str, list[str]]] = None,
468
+ preload_module_classes: Optional[list[str]] = None,
469
+ tied_params_map: Optional[dict[int, dict[torch.device, torch.Tensor]]] = None,
470
+ ):
471
+ """
472
+ Recursively attaches `AlignDevicesHook` to all submodules of a given model that have direct parameters and/or
473
+ buffers.
474
+
475
+ Args:
476
+ module (`torch.nn.Module`):
477
+ The module where we want to attach the hooks.
478
+ execution_device (`torch.device`, *optional*):
479
+ The device on which inputs and model weights should be placed before the forward pass.
480
+ offload (`bool`, *optional*, defaults to `False`):
481
+ Whether or not the weights should be offloaded after the forward pass.
482
+ weights_map (`Mapping[str, torch.Tensor]`, *optional*):
483
+ When the model weights are offloaded, a (potentially lazy) map from param names to the tensor values.
484
+ offload_buffers (`bool`, *optional*, defaults to `False`):
485
+ Whether or not to include the associated module's buffers when offloading.
486
+ module_name (`str`, *optional*, defaults to `""`):
487
+ The name of the module.
488
+ skip_keys (`str` or `List[str]`, *optional*):
489
+ A list of keys to ignore when moving inputs or outputs between devices.
490
+ preload_module_classes (`List[str]`, *optional*):
491
+ A list of classes whose instances should load all their weights (even in the submodules) at the beginning
492
+ of the forward. This should only be used for classes that have submodules which are registered but not
493
+ called directly during the forward, for instance if a `dense` linear layer is registered, but at forward,
494
+ `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly.
495
+ tied_params_map (Optional[Dict[int, Dict[torch.device, torch.Tensor]]], *optional*, defaults to `None`):
496
+ A map of data pointers to dictionaries of devices to already dispatched tied weights. For a given execution
497
+ device, this parameter is useful to reuse the first available pointer of a shared weight for all others,
498
+ instead of duplicating memory.
499
+ """
500
+ # Attach the hook on this module if it has any direct tensor.
501
+ directs = named_module_tensors(module)
502
+ full_offload = (
503
+ offload and preload_module_classes is not None and module.__class__.__name__ in preload_module_classes
504
+ )
505
+
506
+ if len(list(directs)) > 0 or full_offload:
507
+ if weights_map is not None:
508
+ prefix = f"{module_name}." if len(module_name) > 0 else ""
509
+ prefixed_weights_map = PrefixedDataset(weights_map, prefix)
510
+ else:
511
+ prefixed_weights_map = None
512
+ hook = AlignDevicesHook(
513
+ execution_device=execution_device,
514
+ offload=offload,
515
+ weights_map=prefixed_weights_map,
516
+ offload_buffers=offload_buffers,
517
+ place_submodules=full_offload,
518
+ skip_keys=skip_keys,
519
+ tied_params_map=tied_params_map,
520
+ )
521
+ add_hook_to_module(module, hook, append=True)
522
+
523
+ # We stop the recursion in case we hit the full offload.
524
+ if full_offload:
525
+ return
526
+
527
+ # Recurse on all children of the module.
528
+ for child_name, child in module.named_children():
529
+ child_name = f"{module_name}.{child_name}" if len(module_name) > 0 else child_name
530
+ attach_align_device_hook(
531
+ child,
532
+ execution_device=execution_device,
533
+ offload=offload,
534
+ weights_map=weights_map,
535
+ offload_buffers=offload_buffers,
536
+ module_name=child_name,
537
+ preload_module_classes=preload_module_classes,
538
+ skip_keys=skip_keys,
539
+ tied_params_map=tied_params_map,
540
+ )
541
+
542
+
543
+ def remove_hook_from_submodules(module: nn.Module):
544
+ """
545
+ Recursively removes all hooks attached on the submodules of a given model.
546
+
547
+ Args:
548
+ module (`torch.nn.Module`): The module on which to remove all hooks.
549
+ """
550
+ remove_hook_from_module(module)
551
+ for child in module.children():
552
+ remove_hook_from_submodules(child)
553
+
554
+
555
+ def attach_align_device_hook_on_blocks(
556
+ module: nn.Module,
557
+ execution_device: Optional[Union[torch.device, dict[str, torch.device]]] = None,
558
+ offload: Union[bool, dict[str, bool]] = False,
559
+ weights_map: Mapping = None,
560
+ offload_buffers: bool = False,
561
+ module_name: str = "",
562
+ skip_keys: Optional[Union[str, list[str]]] = None,
563
+ preload_module_classes: Optional[list[str]] = None,
564
+ tied_params_map: Optional[dict[int, dict[torch.device, torch.Tensor]]] = None,
565
+ ):
566
+ """
567
+ Attaches `AlignDevicesHook` to all blocks of a given model as needed.
568
+
569
+ Args:
570
+ module (`torch.nn.Module`):
571
+ The module where we want to attach the hooks.
572
+ execution_device (`torch.device` or `Dict[str, torch.device]`, *optional*):
573
+ The device on which inputs and model weights should be placed before the forward pass. It can be one device
574
+ for the whole module, or a dictionary mapping module name to device.
575
+ offload (`bool`, *optional*, defaults to `False`):
576
+ Whether or not the weights should be offloaded after the forward pass. It can be one boolean for the whole
577
+ module, or a dictionary mapping module name to boolean.
578
+ weights_map (`Mapping[str, torch.Tensor]`, *optional*):
579
+ When the model weights are offloaded, a (potentially lazy) map from param names to the tensor values.
580
+ offload_buffers (`bool`, *optional*, defaults to `False`):
581
+ Whether or not to include the associated module's buffers when offloading.
582
+ module_name (`str`, *optional*, defaults to `""`):
583
+ The name of the module.
584
+ skip_keys (`str` or `List[str]`, *optional*):
585
+ A list of keys to ignore when moving inputs or outputs between devices.
586
+ preload_module_classes (`List[str]`, *optional*):
587
+ A list of classes whose instances should load all their weights (even in the submodules) at the beginning
588
+ of the forward. This should only be used for classes that have submodules which are registered but not
589
+ called directly during the forward, for instance if a `dense` linear layer is registered, but at forward,
590
+ `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly.
591
+ tied_params_map (Optional[Dict[int, Dict[torch.device, torch.Tensor]]], *optional*, defaults to `None`):
592
+ A map of data pointers to dictionaries of devices to already dispatched tied weights. For a given execution
593
+ device, this parameter is useful to reuse the first available pointer of a shared weight for all others,
594
+ instead of duplicating memory.
595
+ """
596
+ # If one device and one offload, we've got one hook.
597
+ if not isinstance(execution_device, Mapping) and not isinstance(offload, dict):
598
+ if not offload:
599
+ hook = AlignDevicesHook(
600
+ execution_device=execution_device,
601
+ io_same_device=True,
602
+ skip_keys=skip_keys,
603
+ place_submodules=True,
604
+ tied_params_map=tied_params_map,
605
+ )
606
+ add_hook_to_module(module, hook)
607
+ else:
608
+ attach_align_device_hook(
609
+ module,
610
+ execution_device=execution_device,
611
+ offload=True,
612
+ weights_map=weights_map,
613
+ offload_buffers=offload_buffers,
614
+ module_name=module_name,
615
+ skip_keys=skip_keys,
616
+ tied_params_map=tied_params_map,
617
+ )
618
+ return
619
+
620
+ if not isinstance(execution_device, Mapping):
621
+ execution_device = {key: execution_device for key in offload.keys()}
622
+ if not isinstance(offload, Mapping):
623
+ offload = {key: offload for key in execution_device.keys()}
624
+
625
+ if module_name in execution_device and module_name in offload and not offload[module_name]:
626
+ hook = AlignDevicesHook(
627
+ execution_device=execution_device[module_name],
628
+ offload_buffers=offload_buffers,
629
+ io_same_device=(module_name == ""),
630
+ place_submodules=True,
631
+ skip_keys=skip_keys,
632
+ tied_params_map=tied_params_map,
633
+ )
634
+ add_hook_to_module(module, hook)
635
+ attach_execution_device_hook(
636
+ module, execution_device[module_name], skip_keys=skip_keys, tied_params_map=tied_params_map
637
+ )
638
+ elif module_name in execution_device and module_name in offload:
639
+ attach_align_device_hook(
640
+ module,
641
+ execution_device=execution_device[module_name],
642
+ offload=True,
643
+ weights_map=weights_map,
644
+ offload_buffers=offload_buffers,
645
+ module_name=module_name,
646
+ skip_keys=skip_keys,
647
+ preload_module_classes=preload_module_classes,
648
+ tied_params_map=tied_params_map,
649
+ )
650
+ if not hasattr(module, "_hf_hook"):
651
+ hook = AlignDevicesHook(
652
+ execution_device=execution_device[module_name],
653
+ io_same_device=(module_name == ""),
654
+ skip_keys=skip_keys,
655
+ tied_params_map=tied_params_map,
656
+ )
657
+ add_hook_to_module(module, hook)
658
+ attach_execution_device_hook(
659
+ module,
660
+ execution_device[module_name],
661
+ preload_module_classes=preload_module_classes,
662
+ skip_keys=skip_keys,
663
+ tied_params_map=tied_params_map,
664
+ )
665
+ elif module_name == "":
666
+ hook = AlignDevicesHook(
667
+ execution_device=execution_device.get(""),
668
+ io_same_device=True,
669
+ skip_keys=skip_keys,
670
+ tied_params_map=tied_params_map,
671
+ )
672
+ add_hook_to_module(module, hook)
673
+
674
+ for child_name, child in module.named_children():
675
+ child_name = f"{module_name}.{child_name}" if len(module_name) > 0 else child_name
676
+ attach_align_device_hook_on_blocks(
677
+ child,
678
+ execution_device=execution_device,
679
+ offload=offload,
680
+ weights_map=weights_map,
681
+ offload_buffers=offload_buffers,
682
+ module_name=child_name,
683
+ preload_module_classes=preload_module_classes,
684
+ skip_keys=skip_keys,
685
+ tied_params_map=tied_params_map,
686
+ )
687
+
688
+
689
+ class CpuOffload(ModelHook):
690
+ """
691
+ Offloads a model on the CPU until its forward pass is called. The model will not be offloaded back to the CPU after
692
+ the forward, the user needs to call the `init_hook` method again for this.
693
+
694
+ Args:
695
+ execution_device(`str`, `int` or `torch.device`, *optional*):
696
+ The device on which the model should be executed. Will default to the MPS device if it's available, then
697
+ GPU 0 if there is a GPU, and finally to the CPU.
698
+ prev_module_hook (`UserCpuOffloadHook`, *optional*):
699
+ The hook sent back by [`cpu_offload_with_hook`] for a previous model in the pipeline you are running. If
700
+ passed, its offload method will be called just before the forward of the model to which this hook is
701
+ attached.
702
+ """
703
+
704
+ def __init__(
705
+ self,
706
+ execution_device: Optional[Union[str, int, torch.device]] = None,
707
+ prev_module_hook: Optional["UserCpuOffloadHook"] = None,
708
+ ):
709
+ self.prev_module_hook = prev_module_hook
710
+
711
+ self.execution_device = execution_device if execution_device is not None else PartialState().default_device
712
+
713
+ def init_hook(self, module):
714
+ return module.to("cpu")
715
+
716
+ def pre_forward(self, module, *args, **kwargs):
717
+ if self.prev_module_hook is not None:
718
+ self.prev_module_hook.offload()
719
+ clear_device_cache()
720
+ module.to(self.execution_device)
721
+ return send_to_device(args, self.execution_device), send_to_device(kwargs, self.execution_device)
722
+
723
+
724
+ class UserCpuOffloadHook:
725
+ """
726
+ A simple hook grouping a model and a `ModelHook`, which provides easy APIs for to call the init method of the hook
727
+ or remove it entirely.
728
+ """
729
+
730
+ def __init__(self, model, hook):
731
+ self.model = model
732
+ self.hook = hook
733
+
734
+ def offload(self):
735
+ self.hook.init_hook(self.model)
736
+
737
+ def remove(self):
738
+ remove_hook_from_module(self.model)
739
+
740
+
741
+ class LayerwiseCastingHook(ModelHook):
742
+ r"""
743
+ A hook that casts the weights of a module to a high precision dtype for computation, and to a low precision dtype
744
+ for storage. This process may lead to quality loss in the output, but can significantly reduce the memory
745
+ footprint.
746
+ """
747
+
748
+ _is_stateful = False
749
+
750
+ def __init__(self, storage_dtype: torch.dtype, compute_dtype: torch.dtype, non_blocking: bool) -> None:
751
+ self.storage_dtype = storage_dtype
752
+ self.compute_dtype = compute_dtype
753
+ self.non_blocking = non_blocking
754
+
755
+ def init_hook(self, module: torch.nn.Module):
756
+ module.to(dtype=self.storage_dtype, non_blocking=self.non_blocking)
757
+ return module
758
+
759
+ def pre_forward(self, module: torch.nn.Module, *args, **kwargs):
760
+ module.to(dtype=self.compute_dtype, non_blocking=self.non_blocking)
761
+ return args, kwargs
762
+
763
+ def post_forward(self, module: torch.nn.Module, output):
764
+ module.to(dtype=self.storage_dtype, non_blocking=self.non_blocking)
765
+ return output
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/inference.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import math
15
+ from types import MethodType
16
+ from typing import Any, Optional, Union
17
+
18
+ from .state import PartialState
19
+ from .utils import (
20
+ calculate_maximum_sizes,
21
+ convert_bytes,
22
+ copy_tensor_to_devices,
23
+ ignorant_find_batch_size,
24
+ infer_auto_device_map,
25
+ is_pippy_available,
26
+ pad_input_tensors,
27
+ send_to_device,
28
+ )
29
+
30
+
31
+ def generate_device_map(model, num_processes: int = 1, no_split_module_classes=None, max_memory: dict = None):
32
+ """
33
+ Calculates the device map for `model` with an offset for PiPPy
34
+ """
35
+ if num_processes == 1:
36
+ return infer_auto_device_map(model, no_split_module_classes=no_split_module_classes, clean_result=False)
37
+ if max_memory is None:
38
+ model_size, shared = calculate_maximum_sizes(model)
39
+
40
+ # Split into `n` chunks for each GPU
41
+ memory = (model_size + shared[0]) / num_processes
42
+ memory = convert_bytes(memory)
43
+ value, ending = memory.split(" ")
44
+
45
+ # Add a chunk to deal with potential extra shared memory instances
46
+ memory = math.ceil(float(value)) * 1.1
47
+ memory = f"{memory} {ending}"
48
+ max_memory = {i: memory for i in range(num_processes)}
49
+ device_map = infer_auto_device_map(
50
+ model,
51
+ max_memory=max_memory,
52
+ no_split_module_classes=no_split_module_classes,
53
+ clean_result=False,
54
+ )
55
+ return device_map
56
+
57
+
58
+ def find_pippy_batch_size(args, kwargs):
59
+ found_batch_size = None
60
+ if args is not None:
61
+ for arg in args:
62
+ found_batch_size = ignorant_find_batch_size(arg)
63
+ if found_batch_size is not None:
64
+ break
65
+ if kwargs is not None and found_batch_size is None:
66
+ for kwarg in kwargs.values():
67
+ found_batch_size = ignorant_find_batch_size(kwarg)
68
+ if found_batch_size is not None:
69
+ break
70
+ return found_batch_size
71
+
72
+
73
+ def build_pipeline(model, split_points, args, kwargs, num_chunks):
74
+ """
75
+ Attaches the split points to the model based on `self.device_map` and generates a `PipelineStage`. Requires passing
76
+ in needed `args` and `kwargs` as the model needs on the CPU.
77
+
78
+ Users can pass in custom `num_chunks` as an optional hyper-parameter. By default will use
79
+ `AcceleratorState.num_processes`
80
+ """
81
+ # Note: We import here to reduce import time from general modules, and isolate outside dependencies
82
+ from torch.distributed.pipelining import ScheduleGPipe, SplitPoint, pipeline
83
+
84
+ # We need to annotate the split points in the model for PiPPy
85
+ state = PartialState()
86
+ split_spec = {split_point: SplitPoint.BEGINNING for split_point in split_points}
87
+ pipe = pipeline(
88
+ model,
89
+ mb_args=args,
90
+ mb_kwargs=kwargs,
91
+ split_spec=split_spec,
92
+ )
93
+ stage = pipe.build_stage(state.local_process_index, device=state.device)
94
+ schedule = ScheduleGPipe(stage, num_chunks)
95
+
96
+ return schedule
97
+
98
+
99
+ def pippy_forward(forward, num_chunks, gather_output, *args, **kwargs):
100
+ state = PartialState()
101
+ output = None
102
+
103
+ if state.num_processes == 1:
104
+ output = forward(*args, **kwargs)
105
+ elif state.is_local_main_process:
106
+ found_batch_size = find_pippy_batch_size(args, kwargs)
107
+ if found_batch_size is None:
108
+ raise ValueError("Could not find batch size from args or kwargs")
109
+ else:
110
+ if found_batch_size != num_chunks:
111
+ args = pad_input_tensors(args, found_batch_size, num_chunks)
112
+ kwargs = pad_input_tensors(kwargs, found_batch_size, num_chunks)
113
+ forward(*args, **kwargs)
114
+ elif state.is_last_process:
115
+ output = forward()
116
+ else:
117
+ forward()
118
+ if gather_output:
119
+ # Each node will get a copy of the full output which is only on the last GPU
120
+ output = copy_tensor_to_devices(output)
121
+ return output
122
+
123
+
124
+ def prepare_pippy(
125
+ model,
126
+ split_points: Optional[Union[str, list[str]]] = "auto",
127
+ no_split_module_classes: Optional[list[str]] = None,
128
+ example_args: Optional[tuple[Any]] = (),
129
+ example_kwargs: Optional[dict[str, Any]] = None,
130
+ num_chunks: Optional[int] = None,
131
+ gather_output: Optional[bool] = False,
132
+ ):
133
+ """
134
+ Wraps `model` for pipeline parallel inference.
135
+
136
+ Args:
137
+ model (`torch.nn.Module`):
138
+ A model we want to split for pipeline-parallel inference
139
+ split_points (`str` or `List[str]`, defaults to 'auto'):
140
+ How to generate the split points and chunk the model across each GPU. 'auto' will find the best balanced
141
+ split given any model. Should be a list of layer names in the model to split by otherwise.
142
+ no_split_module_classes (`List[str]`):
143
+ A list of class names for layers we don't want to be split.
144
+ example_args (tuple of model inputs):
145
+ The expected inputs for the model that uses order-based inputs for a *single process*. Recommended to use
146
+ this method if possible.
147
+ example_kwargs (dict of model inputs)
148
+ The expected inputs for the model that uses dictionary-based inputs for a *single process*. This is a
149
+ *highly* limiting structure that requires the same keys be present at *all* inference calls. Not
150
+ recommended unless the prior condition is true for all cases.
151
+ num_chunks (`int`, defaults to the number of available GPUs):
152
+ The number of different stages the Pipeline will have. By default it will assign one chunk per GPU, but
153
+ this can be tuned and played with. In general one should have num_chunks >= num_gpus.
154
+ gather_output (`bool`, defaults to `False`):
155
+ If `True`, the output from the last GPU (which holds the true outputs) is sent across to all GPUs.
156
+ """
157
+ if not is_pippy_available():
158
+ raise ImportError("Using `torch.distributed.pipelining` requires PyTorch 2.4.0 or later.")
159
+ state = PartialState()
160
+ example_args = send_to_device(example_args, "cpu")
161
+ example_kwargs = send_to_device(example_kwargs, "cpu")
162
+ if num_chunks is None:
163
+ num_chunks = state.num_processes
164
+ if split_points == "auto":
165
+ device_map = generate_device_map(model, num_chunks, no_split_module_classes=no_split_module_classes)
166
+ split_points = []
167
+ for i in range(1, num_chunks):
168
+ split_points.append(next(k for k, v in device_map.items() if v == i))
169
+ model.hf_split_points = split_points
170
+ stage = build_pipeline(model, split_points, example_args, example_kwargs, num_chunks)
171
+ model._original_forward = model.forward
172
+ model._original_call = model.__call__
173
+ model.pippy_stage = stage
174
+ model.hf_split_points = split_points
175
+
176
+ def forward(*args, **kwargs):
177
+ return pippy_forward(stage.step, num_chunks, gather_output, *args, **kwargs)
178
+
179
+ # To act like a decorator so that it can be popped when doing `extract_model_from_parallel`
180
+ # Note: creates an infinite recursion loop with `generate`
181
+ model_forward = MethodType(forward, model)
182
+ forward.__wrapped__ = model_forward
183
+ model.forward = forward
184
+ return model
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/launchers.py ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+ import sys
17
+ import tempfile
18
+
19
+ import torch
20
+
21
+ from .state import AcceleratorState, PartialState
22
+ from .utils import (
23
+ PrecisionType,
24
+ PrepareForLaunch,
25
+ are_libraries_initialized,
26
+ check_cuda_p2p_ib_support,
27
+ get_gpu_info,
28
+ is_mps_available,
29
+ is_torch_version,
30
+ patch_environment,
31
+ )
32
+ from .utils.constants import ELASTIC_LOG_LINE_PREFIX_TEMPLATE_PYTORCH_VERSION
33
+
34
+
35
+ def test_launch():
36
+ "Verify a `PartialState` can be initialized."
37
+ _ = PartialState()
38
+
39
+
40
+ def notebook_launcher(
41
+ function,
42
+ args=(),
43
+ num_processes=None,
44
+ mixed_precision="no",
45
+ use_port="29500",
46
+ master_addr="127.0.0.1",
47
+ node_rank=0,
48
+ num_nodes=1,
49
+ rdzv_backend="static",
50
+ rdzv_endpoint="",
51
+ rdzv_conf=None,
52
+ rdzv_id="none",
53
+ max_restarts=0,
54
+ monitor_interval=0.1,
55
+ log_line_prefix_template=None,
56
+ ):
57
+ """
58
+ Launches a training function, using several processes or multiple nodes if it's possible in the current environment
59
+ (TPU with multiple cores for instance).
60
+
61
+ <Tip warning={true}>
62
+
63
+ To use this function absolutely zero calls to a device must be made in the notebook session before calling. If any
64
+ have been made, you will need to restart the notebook and make sure no cells use any device capability.
65
+
66
+ Setting `ACCELERATE_DEBUG_MODE="1"` in your environment will run a test before truly launching to ensure that none
67
+ of those calls have been made.
68
+
69
+ </Tip>
70
+
71
+ Args:
72
+ function (`Callable`):
73
+ The training function to execute. If it accepts arguments, the first argument should be the index of the
74
+ process run.
75
+ args (`Tuple`):
76
+ Tuple of arguments to pass to the function (it will receive `*args`).
77
+ num_processes (`int`, *optional*):
78
+ The number of processes to use for training. Will default to 8 in Colab/Kaggle if a TPU is available, to
79
+ the number of devices available otherwise.
80
+ mixed_precision (`str`, *optional*, defaults to `"no"`):
81
+ If `fp16` or `bf16`, will use mixed precision training on multi-device.
82
+ use_port (`str`, *optional*, defaults to `"29500"`):
83
+ The port to use to communicate between processes when launching a multi-device training.
84
+ master_addr (`str`, *optional*, defaults to `"127.0.0.1"`):
85
+ The address to use for communication between processes.
86
+ node_rank (`int`, *optional*, defaults to 0):
87
+ The rank of the current node.
88
+ num_nodes (`int`, *optional*, defaults to 1):
89
+ The number of nodes to use for training.
90
+ rdzv_backend (`str`, *optional*, defaults to `"static"`):
91
+ The rendezvous method to use, such as 'static' (the default) or 'c10d'
92
+ rdzv_endpoint (`str`, *optional*, defaults to `""`):
93
+ The endpoint of the rdzv sync. storage.
94
+ rdzv_conf (`Dict`, *optional*, defaults to `None`):
95
+ Additional rendezvous configuration.
96
+ rdzv_id (`str`, *optional*, defaults to `"none"`):
97
+ The unique run id of the job.
98
+ max_restarts (`int`, *optional*, defaults to 0):
99
+ The maximum amount of restarts that elastic agent will conduct on workers before failure.
100
+ monitor_interval (`float`, *optional*, defaults to 0.1):
101
+ The interval in seconds that is used by the elastic_agent as a period of monitoring workers.
102
+ log_line_prefix_template (`str`, *optional*, defaults to `None`):
103
+ The prefix template for elastic launch logging. Available from PyTorch 2.2.0.
104
+
105
+ Example:
106
+
107
+ ```python
108
+ # Assume this is defined in a Jupyter Notebook on an instance with two devices
109
+ from accelerate import notebook_launcher
110
+
111
+
112
+ def train(*args):
113
+ # Your training function here
114
+ ...
115
+
116
+
117
+ notebook_launcher(train, args=(arg1, arg2), num_processes=2, mixed_precision="fp16")
118
+ ```
119
+ """
120
+ # Are we in a google colab or a Kaggle Kernel?
121
+ in_colab = False
122
+ in_kaggle = False
123
+ if any(key.startswith("KAGGLE") for key in os.environ.keys()):
124
+ in_kaggle = True
125
+ elif "IPython" in sys.modules:
126
+ in_colab = "google.colab" in str(sys.modules["IPython"].get_ipython())
127
+
128
+ try:
129
+ mixed_precision = PrecisionType(mixed_precision.lower())
130
+ except ValueError:
131
+ raise ValueError(
132
+ f"Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}."
133
+ )
134
+
135
+ if (in_colab or in_kaggle) and (
136
+ (os.environ.get("TPU_NAME", None) is not None) or (os.environ.get("PJRT_DEVICE", "") == "TPU")
137
+ ):
138
+ # TPU launch
139
+ import torch_xla.distributed.xla_multiprocessing as xmp
140
+
141
+ if len(AcceleratorState._shared_state) > 0:
142
+ raise ValueError(
143
+ "To train on TPU in Colab or Kaggle Kernel, the `Accelerator` should only be initialized inside "
144
+ "your training function. Restart your notebook and make sure no cells initializes an "
145
+ "`Accelerator`."
146
+ )
147
+
148
+ launcher = PrepareForLaunch(function, distributed_type="XLA")
149
+ print("Launching a training on TPU cores.")
150
+ xmp.spawn(launcher, args=args, start_method="fork")
151
+ elif in_colab and get_gpu_info()[1] < 2:
152
+ # No need for a distributed launch otherwise as it's either CPU or one GPU.
153
+ if torch.cuda.is_available():
154
+ print("Launching training on one GPU.")
155
+ else:
156
+ print("Launching training on one CPU.")
157
+ function(*args)
158
+ else:
159
+ if num_processes is None:
160
+ raise ValueError(
161
+ "You have to specify the number of devices you would like to use, add `num_processes=...` to your call."
162
+ )
163
+ if node_rank >= num_nodes:
164
+ raise ValueError("The node_rank must be less than the number of nodes.")
165
+ if num_processes > 1:
166
+ # Multi-device launch
167
+ from torch.distributed.launcher.api import LaunchConfig, elastic_launch
168
+ from torch.multiprocessing import start_processes
169
+ from torch.multiprocessing.spawn import ProcessRaisedException
170
+
171
+ if len(AcceleratorState._shared_state) > 0:
172
+ raise ValueError(
173
+ "To launch a multi-device training from your notebook, the `Accelerator` should only be initialized "
174
+ "inside your training function. Restart your notebook and make sure no cells initializes an "
175
+ "`Accelerator`."
176
+ )
177
+ # Check for specific libraries known to initialize device that users constantly use
178
+ problematic_imports = are_libraries_initialized("bitsandbytes")
179
+ if len(problematic_imports) > 0:
180
+ err = (
181
+ "Could not start distributed process. Libraries known to initialize device upon import have been "
182
+ "imported already. Please keep these imports inside your training function to try and help with this:"
183
+ )
184
+ for lib_name in problematic_imports:
185
+ err += f"\n\t* `{lib_name}`"
186
+ raise RuntimeError(err)
187
+
188
+ patched_env = dict(
189
+ nproc=num_processes,
190
+ node_rank=node_rank,
191
+ world_size=num_nodes * num_processes,
192
+ master_addr=master_addr,
193
+ master_port=use_port,
194
+ mixed_precision=mixed_precision,
195
+ )
196
+
197
+ # Check for CUDA P2P and IB issues
198
+ if not check_cuda_p2p_ib_support():
199
+ patched_env["nccl_p2p_disable"] = "1"
200
+ patched_env["nccl_ib_disable"] = "1"
201
+
202
+ # torch.distributed will expect a few environment variable to be here. We set the ones common to each
203
+ # process here (the other ones will be set be the launcher).
204
+ with patch_environment(**patched_env):
205
+ # First dummy launch
206
+ device_type = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda"
207
+ distributed_type = "MULTI_XPU" if device_type == "xpu" else "MULTI_GPU"
208
+ if os.environ.get("ACCELERATE_DEBUG_MODE", "false").lower() == "true":
209
+ launcher = PrepareForLaunch(test_launch, distributed_type=distributed_type)
210
+ try:
211
+ start_processes(launcher, args=(), nprocs=num_processes, start_method="fork")
212
+ except ProcessRaisedException as e:
213
+ err = "An issue was found when verifying a stable environment for the notebook launcher."
214
+ if f"Cannot re-initialize {device_type.upper()} in forked subprocess" in e.args[0]:
215
+ raise RuntimeError(
216
+ f"{err}"
217
+ "This likely stems from an outside import causing issues once the `notebook_launcher()` is called. "
218
+ "Please review your imports and test them when running the `notebook_launcher()` to identify "
219
+ f"which one is problematic and causing {device_type.upper()} to be initialized."
220
+ ) from e
221
+ else:
222
+ raise RuntimeError(f"{err} The following error was raised: {e}") from e
223
+ # Now the actual launch
224
+ launcher = PrepareForLaunch(function, distributed_type=distributed_type)
225
+ print(f"Launching training on {num_processes} {device_type.upper()}s.")
226
+ try:
227
+ if rdzv_conf is None:
228
+ rdzv_conf = {}
229
+ if rdzv_backend == "static":
230
+ rdzv_conf["rank"] = node_rank
231
+ if not rdzv_endpoint:
232
+ rdzv_endpoint = f"{master_addr}:{use_port}"
233
+ launch_config_kwargs = dict(
234
+ min_nodes=num_nodes,
235
+ max_nodes=num_nodes,
236
+ nproc_per_node=num_processes,
237
+ run_id=rdzv_id,
238
+ rdzv_endpoint=rdzv_endpoint,
239
+ rdzv_backend=rdzv_backend,
240
+ rdzv_configs=rdzv_conf,
241
+ max_restarts=max_restarts,
242
+ monitor_interval=monitor_interval,
243
+ start_method="fork",
244
+ )
245
+ if is_torch_version(">=", ELASTIC_LOG_LINE_PREFIX_TEMPLATE_PYTORCH_VERSION):
246
+ launch_config_kwargs["log_line_prefix_template"] = log_line_prefix_template
247
+ elastic_launch(config=LaunchConfig(**launch_config_kwargs), entrypoint=function)(*args)
248
+ except ProcessRaisedException as e:
249
+ if f"Cannot re-initialize {device_type.upper()} in forked subprocess" in e.args[0]:
250
+ raise RuntimeError(
251
+ f"{device_type.upper()} has been initialized before the `notebook_launcher` could create a forked subprocess. "
252
+ "This likely stems from an outside import causing issues once the `notebook_launcher()` is called. "
253
+ "Please review your imports and test them when running the `notebook_launcher()` to identify "
254
+ f"which one is problematic and causing {device_type.upper()} to be initialized."
255
+ ) from e
256
+ else:
257
+ raise RuntimeError(f"An issue was found when launching the training: {e}") from e
258
+
259
+ else:
260
+ # No need for a distributed launch otherwise as it's either CPU, GPU, XPU or MPS.
261
+ if is_mps_available():
262
+ os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
263
+ print("Launching training on MPS.")
264
+ elif torch.cuda.is_available():
265
+ print("Launching training on one GPU.")
266
+ elif torch.xpu.is_available():
267
+ print("Launching training on one XPU.")
268
+ else:
269
+ print("Launching training on CPU.")
270
+ function(*args)
271
+
272
+
273
+ def debug_launcher(function, args=(), num_processes=2):
274
+ """
275
+ Launches a training function using several processes on CPU for debugging purposes.
276
+
277
+ <Tip warning={true}>
278
+
279
+ This function is provided for internal testing and debugging, but it's not intended for real trainings. It will
280
+ only use the CPU.
281
+
282
+ </Tip>
283
+
284
+ Args:
285
+ function (`Callable`):
286
+ The training function to execute.
287
+ args (`Tuple`):
288
+ Tuple of arguments to pass to the function (it will receive `*args`).
289
+ num_processes (`int`, *optional*, defaults to 2):
290
+ The number of processes to use for training.
291
+ """
292
+ from torch.multiprocessing import start_processes
293
+
294
+ with tempfile.NamedTemporaryFile() as tmp_file:
295
+ # torch.distributed will expect a few environment variable to be here. We set the ones common to each
296
+ # process here (the other ones will be set be the launcher).
297
+ with patch_environment(
298
+ world_size=num_processes,
299
+ master_addr="127.0.0.1",
300
+ master_port="29500",
301
+ accelerate_mixed_precision="no",
302
+ accelerate_debug_rdv_file=tmp_file.name,
303
+ accelerate_use_cpu="yes",
304
+ ):
305
+ launcher = PrepareForLaunch(function, debug=True)
306
+ start_processes(launcher, args=args, nprocs=num_processes, start_method="fork")
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/local_sgd.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import torch
15
+
16
+ from accelerate import Accelerator, DistributedType
17
+
18
+
19
+ class LocalSGD:
20
+ """
21
+ A helper class to support local SGD on top of Accelerator. It simply runs a given number of updates independently
22
+ on each device, and averages model weights every K synchronization step.
23
+
24
+ It should be used only in the multi-GPU (or multi-CPU) setup without extensions such as DeepSpeed. In particular,
25
+ this is a simple implementation that cannot support scenarios such as model parallelism.
26
+
27
+
28
+ Although we are not aware of the true origins of this simple approach, the idea of local SGD is quite old and goes
29
+ back to at least:
30
+
31
+ Zhang, J., De Sa, C., Mitliagkas, I., & Ré, C. (2016). [Parallel SGD: When does averaging help?. arXiv preprint
32
+ arXiv:1606.07365.](https://arxiv.org/abs/1606.07365)
33
+
34
+ We credit the term Local SGD to the following paper (but there might be earlier references we are not aware of).
35
+
36
+ Stich, Sebastian Urban. ["Local SGD Converges Fast and Communicates Little." ICLR 2019-International Conference on
37
+ Learning Representations. No. CONF. 2019.](https://arxiv.org/abs/1805.09767)
38
+
39
+ """
40
+
41
+ def __enter__(self):
42
+ if self.enabled:
43
+ self.model_sync_obj = self.model.no_sync()
44
+ self.model_sync_obj.__enter__()
45
+
46
+ return self
47
+
48
+ def __exit__(self, type, value, tb):
49
+ if self.enabled:
50
+ # Average all models on exit
51
+ self._sync_and_avg_model_params()
52
+ self.model_sync_obj.__exit__(type, value, tb)
53
+
54
+ def __init__(self, accelerator: Accelerator, model: torch.nn.Module, local_sgd_steps: int, enabled: bool = True):
55
+ """
56
+ Constructor.
57
+
58
+ Args:
59
+ model (`torch.nn.Module):
60
+ The model whose parameters we need to average.
61
+ accelerator (`Accelerator`):
62
+ Accelerator object.
63
+ local_sgd_steps (`int`):
64
+ A number of local SGD steps (before model parameters are synchronized).
65
+ enabled (`bool):
66
+ Local SGD is disabled if this parameter set to `False`.
67
+ """
68
+ if accelerator.distributed_type not in [
69
+ DistributedType.NO,
70
+ DistributedType.MULTI_CPU,
71
+ DistributedType.MULTI_GPU,
72
+ DistributedType.MULTI_XPU,
73
+ DistributedType.MULTI_MLU,
74
+ DistributedType.MULTI_HPU,
75
+ DistributedType.MULTI_SDAA,
76
+ DistributedType.MULTI_MUSA,
77
+ DistributedType.MULTI_NPU,
78
+ ]:
79
+ raise NotImplementedError("LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)")
80
+ self.enabled = enabled and accelerator.distributed_type != DistributedType.NO
81
+ self.num_steps = 0
82
+ if self.enabled:
83
+ self.accelerator = accelerator
84
+ self.model = model
85
+ self.local_sgd_steps = local_sgd_steps
86
+
87
+ def step(self):
88
+ """
89
+ This function makes a "step" and synchronizes model parameters if necessary.
90
+ """
91
+ self.num_steps += 1
92
+ if not self.enabled:
93
+ return
94
+
95
+ if self.num_steps % self.local_sgd_steps == 0:
96
+ self._sync_and_avg_model_params()
97
+
98
+ def _sync_and_avg_model_params(self):
99
+ """
100
+ Synchronize + Average model parameters across all GPUs
101
+ """
102
+
103
+ self.accelerator.wait_for_everyone()
104
+ with self.accelerator.autocast():
105
+ for param in self.model.parameters():
106
+ param.data = self.accelerator.reduce(param.data, reduction="mean")
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/logging.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import functools
16
+ import logging
17
+ import os
18
+
19
+ from .state import PartialState
20
+
21
+
22
+ class MultiProcessAdapter(logging.LoggerAdapter):
23
+ """
24
+ An adapter to assist with logging in multiprocess.
25
+
26
+ `log` takes in an additional `main_process_only` kwarg, which dictates whether it should be called on all processes
27
+ or only the main executed one. Default is `main_process_only=True`.
28
+
29
+ Does not require an `Accelerator` object to be created first.
30
+ """
31
+
32
+ @staticmethod
33
+ def _should_log(main_process_only):
34
+ "Check if log should be performed"
35
+ state = PartialState()
36
+ return not main_process_only or (main_process_only and state.is_main_process)
37
+
38
+ def log(self, level, msg, *args, **kwargs):
39
+ """
40
+ Delegates logger call after checking if we should log.
41
+
42
+ Accepts a new kwarg of `main_process_only`, which will dictate whether it will be logged across all processes
43
+ or only the main executed one. Default is `True` if not passed
44
+
45
+ Also accepts "in_order", which if `True` makes the processes log one by one, in order. This is much easier to
46
+ read, but comes at the cost of sometimes needing to wait for the other processes. Default is `False` to not
47
+ break with the previous behavior.
48
+
49
+ `in_order` is ignored if `main_process_only` is passed.
50
+ """
51
+ if PartialState._shared_state == {}:
52
+ raise RuntimeError(
53
+ "You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility."
54
+ )
55
+ main_process_only = kwargs.pop("main_process_only", True)
56
+ in_order = kwargs.pop("in_order", False)
57
+ # set `stacklevel` to exclude ourself in `Logger.findCaller()` while respecting user's choice
58
+ kwargs.setdefault("stacklevel", 2)
59
+
60
+ if self.isEnabledFor(level):
61
+ if self._should_log(main_process_only):
62
+ msg, kwargs = self.process(msg, kwargs)
63
+ self.logger.log(level, msg, *args, **kwargs)
64
+
65
+ elif in_order:
66
+ state = PartialState()
67
+ for i in range(state.num_processes):
68
+ if i == state.process_index:
69
+ msg, kwargs = self.process(msg, kwargs)
70
+ self.logger.log(level, msg, *args, **kwargs)
71
+ state.wait_for_everyone()
72
+
73
+ @functools.lru_cache(None)
74
+ def warning_once(self, *args, **kwargs):
75
+ """
76
+ This method is identical to `logger.warning()`, but will emit the warning with the same message only once
77
+
78
+ Note: The cache is for the function arguments, so 2 different callers using the same arguments will hit the
79
+ cache. The assumption here is that all warning messages are unique across the code. If they aren't then need to
80
+ switch to another type of cache that includes the caller frame information in the hashing function.
81
+ """
82
+ self.warning(*args, **kwargs)
83
+
84
+
85
+ def get_logger(name: str, log_level: str = None):
86
+ """
87
+ Returns a `logging.Logger` for `name` that can handle multiprocessing.
88
+
89
+ If a log should be called on all processes, pass `main_process_only=False` If a log should be called on all
90
+ processes and in order, also pass `in_order=True`
91
+
92
+ Args:
93
+ name (`str`):
94
+ The name for the logger, such as `__file__`
95
+ log_level (`str`, *optional*):
96
+ The log level to use. If not passed, will default to the `LOG_LEVEL` environment variable, or `INFO` if not
97
+
98
+ Example:
99
+
100
+ ```python
101
+ >>> from accelerate.logging import get_logger
102
+ >>> from accelerate import Accelerator
103
+
104
+ >>> logger = get_logger(__name__)
105
+
106
+ >>> accelerator = Accelerator()
107
+ >>> logger.info("My log", main_process_only=False)
108
+ >>> logger.debug("My log", main_process_only=True)
109
+
110
+ >>> logger = get_logger(__name__, log_level="DEBUG")
111
+ >>> logger.info("My log")
112
+ >>> logger.debug("My second log")
113
+
114
+ >>> array = ["a", "b", "c", "d"]
115
+ >>> letter_at_rank = array[accelerator.process_index]
116
+ >>> logger.info(letter_at_rank, in_order=True)
117
+ ```
118
+ """
119
+ if log_level is None:
120
+ log_level = os.environ.get("ACCELERATE_LOG_LEVEL", None)
121
+ logger = logging.getLogger(name)
122
+ if log_level is not None:
123
+ logger.setLevel(log_level.upper())
124
+ logger.root.setLevel(log_level.upper())
125
+ return MultiProcessAdapter(logger, {})
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/memory_utils.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import warnings
16
+
17
+
18
+ warnings.warn(
19
+ "memory_utils has been reorganized to utils.memory. Import `find_executable_batchsize` from the main `__init__`: "
20
+ "`from accelerate import find_executable_batch_size` to avoid this warning.",
21
+ FutureWarning,
22
+ )
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/optimizer.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+
17
+ import torch
18
+
19
+ from .state import AcceleratorState, GradientState
20
+ from .utils import DistributedType, honor_type, is_lomo_available, is_torch_xla_available
21
+
22
+
23
+ if is_torch_xla_available():
24
+ import torch_xla.core.xla_model as xm
25
+ import torch_xla.runtime as xr
26
+
27
+
28
+ def move_to_device(state, device):
29
+ if isinstance(state, (list, tuple)):
30
+ return honor_type(state, (move_to_device(t, device) for t in state))
31
+ elif isinstance(state, dict):
32
+ return type(state)({k: move_to_device(v, device) for k, v in state.items()})
33
+ elif isinstance(state, torch.Tensor):
34
+ return state.to(device)
35
+ return state
36
+
37
+
38
+ class AcceleratedOptimizer(torch.optim.Optimizer):
39
+ """
40
+ Internal wrapper around a torch optimizer.
41
+
42
+ Conditionally will perform `step` and `zero_grad` if gradients should be synchronized when performing gradient
43
+ accumulation.
44
+
45
+ Args:
46
+ optimizer (`torch.optim.optimizer.Optimizer`):
47
+ The optimizer to wrap.
48
+ device_placement (`bool`, *optional*, defaults to `True`):
49
+ Whether or not the optimizer should handle device placement. If so, it will place the state dictionary of
50
+ `optimizer` on the right device.
51
+ scaler (`torch.amp.GradScaler` or `torch.cuda.amp.GradScaler`, *optional*):
52
+ The scaler to use in the step function if training with mixed precision.
53
+ """
54
+
55
+ def __init__(self, optimizer, device_placement=True, scaler=None):
56
+ self.optimizer = optimizer
57
+ self.scaler = scaler
58
+ self.accelerator_state = AcceleratorState()
59
+ self.gradient_state = GradientState()
60
+ self.device_placement = device_placement
61
+ self._is_overflow = False
62
+
63
+ if self.scaler is not None:
64
+ self._accelerate_step_called = False
65
+ self._optimizer_original_step_method = self.optimizer.step
66
+ self._optimizer_patched_step_method = patch_optimizer_step(self, self.optimizer.step)
67
+
68
+ # Handle device placement
69
+ if device_placement:
70
+ state_dict = self.optimizer.state_dict()
71
+ if self.accelerator_state.distributed_type == DistributedType.XLA:
72
+ xm.send_cpu_data_to_device(state_dict, self.accelerator_state.device)
73
+ else:
74
+ state_dict = move_to_device(state_dict, self.accelerator_state.device)
75
+ self.optimizer.load_state_dict(state_dict)
76
+
77
+ @property
78
+ def state(self):
79
+ return self.optimizer.state
80
+
81
+ @state.setter
82
+ def state(self, state):
83
+ self.optimizer.state = state
84
+
85
+ @property
86
+ def param_groups(self):
87
+ return self.optimizer.param_groups
88
+
89
+ @param_groups.setter
90
+ def param_groups(self, param_groups):
91
+ self.optimizer.param_groups = param_groups
92
+
93
+ @property
94
+ def defaults(self):
95
+ return self.optimizer.defaults
96
+
97
+ @defaults.setter
98
+ def defaults(self, defaults):
99
+ self.optimizer.defaults = defaults
100
+
101
+ def add_param_group(self, param_group):
102
+ self.optimizer.add_param_group(param_group)
103
+
104
+ def load_state_dict(self, state_dict):
105
+ if self.accelerator_state.distributed_type == DistributedType.XLA and self.device_placement:
106
+ xm.send_cpu_data_to_device(state_dict, self.accelerator_state.device)
107
+ self.optimizer.load_state_dict(state_dict)
108
+
109
+ def state_dict(self):
110
+ return self.optimizer.state_dict()
111
+
112
+ def zero_grad(self, set_to_none=None):
113
+ if self.gradient_state.sync_gradients:
114
+ accept_arg = "set_to_none" in inspect.signature(self.optimizer.zero_grad).parameters
115
+ if accept_arg:
116
+ if set_to_none is None:
117
+ set_to_none = True
118
+ self.optimizer.zero_grad(set_to_none=set_to_none)
119
+ else:
120
+ if set_to_none is not None:
121
+ raise ValueError("`set_to_none` for Optimizer.zero_grad` is not supported by this optimizer.")
122
+ self.optimizer.zero_grad()
123
+
124
+ def train(self):
125
+ """
126
+ Sets the optimizer to "train" mode. Useful for optimizers like `schedule_free`
127
+ """
128
+ if hasattr(self.optimizer, "train") and callable(self.optimizer.train):
129
+ self.optimizer.train()
130
+ elif (
131
+ hasattr(self.optimizer, "optimizer")
132
+ and hasattr(self.optimizer.optimizer, "train")
133
+ and callable(self.optimizer.optimizer.train)
134
+ ):
135
+ # the deepspeed optimizer further wraps the optimizer
136
+ self.optimizer.optimizer.train()
137
+
138
+ def eval(self):
139
+ """
140
+ Sets the optimizer to "eval" mode. Useful for optimizers like `schedule_free`
141
+ """
142
+ if hasattr(self.optimizer, "eval") and callable(self.optimizer.eval):
143
+ self.optimizer.eval()
144
+
145
+ def step(self, closure=None):
146
+ if is_lomo_available():
147
+ from lomo_optim import AdaLomo, Lomo
148
+
149
+ if (
150
+ not self.gradient_state.is_xla_gradients_synced
151
+ and self.accelerator_state.distributed_type == DistributedType.XLA
152
+ ):
153
+ gradients = xm._fetch_gradients(self.optimizer)
154
+ xm.all_reduce("sum", gradients, scale=1.0 / xr.world_size())
155
+ self.gradient_state.is_xla_gradients_synced = True
156
+
157
+ if is_lomo_available():
158
+ # `step` should be a no-op for LOMO optimizers.
159
+ if isinstance(self.optimizer, (Lomo, AdaLomo)):
160
+ return
161
+
162
+ if self.gradient_state.sync_gradients:
163
+ if self.scaler is not None:
164
+ self.optimizer.step = self._optimizer_patched_step_method
165
+
166
+ self.scaler.step(self.optimizer, closure)
167
+ self.scaler.update()
168
+
169
+ if not self._accelerate_step_called:
170
+ # If the optimizer step was skipped, gradient overflow was detected.
171
+ self._is_overflow = True
172
+ else:
173
+ self._is_overflow = False
174
+ # Reset the step method to the original one
175
+ self.optimizer.step = self._optimizer_original_step_method
176
+ # Reset the indicator
177
+ self._accelerate_step_called = False
178
+ else:
179
+ self.optimizer.step(closure)
180
+ if self.accelerator_state.distributed_type == DistributedType.XLA:
181
+ self.gradient_state.is_xla_gradients_synced = False
182
+
183
+ def _switch_parameters(self, parameters_map):
184
+ for param_group in self.optimizer.param_groups:
185
+ param_group["params"] = [parameters_map.get(p, p) for p in param_group["params"]]
186
+
187
+ @property
188
+ def step_was_skipped(self):
189
+ """Whether or not the optimizer step was skipped."""
190
+ return self._is_overflow
191
+
192
+ def __getstate__(self):
193
+ _ignored_keys = [
194
+ "_accelerate_step_called",
195
+ "_optimizer_original_step_method",
196
+ "_optimizer_patched_step_method",
197
+ ]
198
+ return {k: v for k, v in self.__dict__.items() if k not in _ignored_keys}
199
+
200
+ def __setstate__(self, state):
201
+ self.__dict__.update(state)
202
+ if self.scaler is not None:
203
+ self._accelerate_step_called = False
204
+ self._optimizer_original_step_method = self.optimizer.step
205
+ self._optimizer_patched_step_method = patch_optimizer_step(self, self.optimizer.step)
206
+
207
+
208
+ def patch_optimizer_step(accelerated_optimizer: AcceleratedOptimizer, method):
209
+ def patched_step(*args, **kwargs):
210
+ accelerated_optimizer._accelerate_step_called = True
211
+ return method(*args, **kwargs)
212
+
213
+ return patched_step
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/parallelism_config.py ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+ import warnings
17
+ from dataclasses import dataclass
18
+ from typing import TYPE_CHECKING, Union
19
+
20
+ from torch.distributed.device_mesh import init_device_mesh
21
+
22
+ from accelerate.utils.dataclasses import TorchContextParallelConfig, TorchTensorParallelConfig
23
+
24
+
25
+ if TYPE_CHECKING:
26
+ from accelerate import Accelerator
27
+
28
+
29
+ @dataclass
30
+ class ParallelismConfig:
31
+ """
32
+ A dataclass to configure parallelisms applied to the model. Inspired by torchtitan's `ParallelDims`
33
+ https://github.com/pytorch/torchtitan/blob/main/torchtitan/distributed/parallel_dims.py
34
+
35
+ Args:
36
+ dp_replicate_size (`int`, defaults to `1`):
37
+ The size of the data parallel group. If `dp_replicate_size` is set to 1, the data parallel replication
38
+ group will not be used.
39
+ dp_shard_size (`int`, defaults to `1`):
40
+ The size of the model shard group. If `dp_replicate_size > 1` and `tp_size > 1`, `dp_shard_size` must also
41
+ be greater than 1, as composing DDP + TP is currently not supported.
42
+ tp_size (`int`, defaults to `1`):
43
+ The size of the tensor parallel group. If `tp_size` is set to `1`, the tensor parallel group will not be
44
+ used.
45
+ cp_size (`int`, defaults to `1`):
46
+ The size of the context parallel group. Currently not supported, but reserved for future use and enabled
47
+ for downstream libraries.
48
+ tp_handler (`~utils.TorchTensorParallelConfig`, defaults to `None`):
49
+ The handler for the tensor parallel group.
50
+
51
+ You may obtain different distributed data parallel paradigms by configuring `dp_replicate_size` and `dp_shard_size`
52
+ together:
53
+ - `dp_replicate_size == 1` and `dp_shard_size > 1`, we obtain Fully Sharded Data Parallel (FSDP).
54
+ - `dp_replicate_size > 1` and `dp_shard_size > 1`, we obtain Hybrid Sharded Data Parallel (HSDP).
55
+ - `dp_replicate_size > 1` and `dp_shard_size == 1` is an invalid configuration, to use pure DP, use
56
+ `DistributedDataParallelKwargs` instead.
57
+
58
+ """
59
+
60
+ dp_replicate_size: int = None
61
+ dp_shard_size: int = None
62
+ tp_size: int = None
63
+ cp_size: int = None
64
+
65
+ # we use Union because we might support other x parallel plugins (i.e. deepspeed, etc)
66
+ tp_handler: Union[None, TorchTensorParallelConfig] = None
67
+ cp_handler: Union[None, TorchContextParallelConfig] = None
68
+
69
+ def __repr__(self):
70
+ return (
71
+ "ParallelismConfig(\n "
72
+ f"\tdp_replicate_size={self.dp_replicate_size},\n"
73
+ f"\tdp_shard_size={self.dp_shard_size},\n"
74
+ f"\ttp_size={self.tp_size},\n"
75
+ f"\tcp_size={self.cp_size},\n"
76
+ f"\ttotal_size={self.total_size}\n"
77
+ f"\ttp_handler={self.tp_handler},\n"
78
+ f"\tcp_handler={self.cp_handler})\n"
79
+ )
80
+
81
+ @property
82
+ def dp_dim_names(self):
83
+ """Names of enabled dimensions across which data parallelism is applied."""
84
+ dims = []
85
+ if self.dp_replicate_enabled:
86
+ dims += ["dp_replicate"]
87
+ if self.dp_shard_enabled:
88
+ dims += ["dp_shard"]
89
+ return dims
90
+
91
+ @property
92
+ def non_dp_dim_names(self):
93
+ """Names of enabled dimensions which will receive the same batch (non-data parallel dimensions)."""
94
+ dims = []
95
+ if self.tp_enabled:
96
+ dims += ["tp"]
97
+ if self.cp_enabled:
98
+ dims += ["cp"]
99
+ return dims
100
+
101
+ @property
102
+ def dp_shard_cp_dim_names(self):
103
+ """Names of enabled dimensions which will be flattened into a joint mesh across which is model sharded in FSDP."""
104
+ dims = []
105
+ if self.dp_shard_enabled:
106
+ dims += ["dp_shard"]
107
+ if self.cp_enabled:
108
+ dims += ["cp"]
109
+ return dims
110
+
111
+ @property
112
+ def dp_cp_dim_names(self):
113
+ """Names of enabled dimensions across which loss should be averaged"""
114
+ dims = []
115
+ if self.dp_replicate_enabled:
116
+ dims += ["dp_replicate"]
117
+ if self.dp_shard_enabled:
118
+ dims += ["dp_shard"]
119
+ if self.cp_enabled:
120
+ dims += ["cp"]
121
+ return dims
122
+
123
+ @property
124
+ def fsdp_dim_names(self):
125
+ """Names of enabled dimensions across which FSDP is applied, including data parallel replication."""
126
+ dims = []
127
+ if self.dp_replicate_enabled:
128
+ dims += ["dp_replicate"]
129
+ dims += ["dp_shard_cp"]
130
+ return dims
131
+
132
+ @property
133
+ def total_size(self):
134
+ """The total size of the parallelism configuration, which is the product of all sizes."""
135
+ return self.dp_replicate_size * self.dp_shard_size * self.tp_size * self.cp_size
136
+
137
+ @property
138
+ def non_data_parallel_size(self):
139
+ """The size of the non-data parallel dimensions, which is the product of tensor and context parallel sizes."""
140
+ return self.tp_size * self.cp_size
141
+
142
+ @property
143
+ def data_parallel_size(self):
144
+ """The size of the data parallel dimensions, which is the product of data parallel replication and"""
145
+ return self.dp_replicate_size * self.dp_shard_size
146
+
147
+ @property
148
+ def dp_replicate_enabled(self):
149
+ """True if data parallel replication is enabled, i.e. `dp_replicate_size > 1`."""
150
+ return self.dp_replicate_size > 1
151
+
152
+ @property
153
+ def dp_shard_enabled(self):
154
+ """True if data parallel sharding is enabled, i.e. `dp_shard_size > 1`."""
155
+ return self.dp_shard_size > 1
156
+
157
+ @property
158
+ def tp_enabled(self):
159
+ """True if tensor parallelism is enabled, i.e. `tp_size > 1`."""
160
+ return self.tp_size > 1
161
+
162
+ @property
163
+ def cp_enabled(self):
164
+ """True if context parallelism is enabled, i.e. `cp_size > 1`."""
165
+ return self.cp_size > 1
166
+
167
+ @property
168
+ def active_mesh_dims(self):
169
+ """Names of all active mesh dimensions."""
170
+ return self.dp_dim_names + self.non_dp_dim_names
171
+
172
+ def build_device_mesh(self, device_type: str):
173
+ """Builds a device mesh for the given device type based on the parallelism configuration.
174
+ This method will also create required joint meshes (e.g. `dp_shard_cp`, `dp_cp`, `dp`).
175
+
176
+ Args:
177
+ device_type (`str`): The type of device for which to build the mesh, e
178
+ """
179
+ mesh = self._get_mesh()
180
+ if len(mesh) == 0:
181
+ return
182
+ mesh_dim_names, mesh_shape = mesh
183
+ device_mesh = init_device_mesh(
184
+ device_type,
185
+ mesh_shape,
186
+ mesh_dim_names=mesh_dim_names,
187
+ )
188
+ if self.dp_dim_names:
189
+ device_mesh[self.dp_dim_names]._flatten("dp")
190
+ if self.dp_shard_cp_dim_names:
191
+ device_mesh[self.dp_shard_cp_dim_names]._flatten("dp_shard_cp")
192
+ if self.dp_cp_dim_names:
193
+ device_mesh[self.dp_cp_dim_names]._flatten("dp_cp")
194
+
195
+ return device_mesh
196
+
197
+ def _get_mesh(self) -> tuple[tuple[int, ...], tuple[str, ...]]:
198
+ """Generate mesh shape and dimension names for torch.distributed.init_device_mesh()."""
199
+
200
+ # Build mesh dimensions dictionary
201
+ mesh_dims = {parallelism: self._sizes[parallelism] for parallelism in self.active_mesh_dims}
202
+
203
+ # Apply canonical ordering
204
+ mesh_order = ["dp_replicate", "dp_shard", "cp", "tp"]
205
+ sorted_items = sorted(
206
+ mesh_dims.items(),
207
+ key=lambda x: (mesh_order.index(x[0])),
208
+ )
209
+ return tuple(zip(*sorted_items))
210
+
211
+ def __post_init__(self):
212
+ # Basic size validation
213
+ if self.dp_replicate_size is None:
214
+ self.dp_replicate_size = int(os.environ.get("PARALLELISM_CONFIG_DP_REPLICATE_SIZE", "1"))
215
+ if self.dp_shard_size is None:
216
+ self.dp_shard_size = int(os.environ.get("PARALLELISM_CONFIG_DP_SHARD_SIZE", "1"))
217
+ if self.tp_size is None:
218
+ self.tp_size = int(os.environ.get("PARALLELISM_CONFIG_TP_SIZE", "1"))
219
+ if self.cp_size is None:
220
+ self.cp_size = int(os.environ.get("PARALLELISM_CONFIG_CP_SIZE", "1"))
221
+
222
+ if self.tp_size > 1:
223
+ if self.tp_handler is None:
224
+ self.tp_handler = TorchTensorParallelConfig()
225
+
226
+ if self.cp_size > 1:
227
+ if self.cp_handler is None:
228
+ self.cp_handler = TorchContextParallelConfig()
229
+
230
+ if self.dp_replicate_size < 1:
231
+ raise ValueError(f"dp_replicate_size must be at least 1, but got {self.dp_replicate_size}")
232
+ if self.dp_shard_size < 1:
233
+ raise ValueError(f"dp_shard_size must be at least 1, but got {self.dp_shard_size}")
234
+ if self.tp_size < 1:
235
+ raise ValueError(f"tp_size must be at least 1, but got {self.tp_size}")
236
+ if self.cp_size < 1:
237
+ raise ValueError(f"cp_size must be at least 1, but got {self.cp_size}")
238
+
239
+ if (self.tp_size > 1 or self.cp_size > 1) and self.dp_replicate_size > 1 and self.dp_shard_size == 1:
240
+ raise ValueError(
241
+ "Tensor/Context parallelism (tp/cp_size > 1) cannot be used with pure data parallelism (dp_replicate_size > 1 and dp_shard_size == 1). "
242
+ "Please set dp_shard_size > 1 and dp_replicate_size == 1 to compose FSDP + TP/CP for 2D parallel, "
243
+ "or set dp_replicate_size == 1 and dp_shard_size > 1 to compose HSDP + TP/CP for 3D parallel."
244
+ )
245
+ self._sizes = {
246
+ "dp_replicate": self.dp_replicate_size,
247
+ "dp_shard": self.dp_shard_size,
248
+ "tp": self.tp_size,
249
+ "cp": self.cp_size,
250
+ }
251
+
252
+ def _set_size(self, parallelism: str, size: int):
253
+ assert parallelism in self._sizes.keys(), f"Parallelism must be one of {self._sizes.keys()}"
254
+ self._sizes[parallelism] = size
255
+ setattr(self, f"{parallelism}_size", size)
256
+
257
+ def _validate_accelerator(self, accelerator: "Accelerator"):
258
+ _warnings = set()
259
+ if not accelerator.multi_device and self.total_size == 1:
260
+ # No distributed setup, valid parallelism config
261
+ return
262
+
263
+ # We need this to ensure DDP works
264
+ if self.total_size == 1:
265
+ self._set_size("dp_replicate", accelerator.num_processes)
266
+
267
+ if self.total_size != accelerator.num_processes:
268
+ raise ValueError(
269
+ f"ParallelismConfig total_size ({self.total_size}) does not match "
270
+ f"num_processes ({accelerator.num_processes}). Please adjust dp_replicate_size/ "
271
+ f"dp_shard_size/tp_size/cp_size."
272
+ )
273
+
274
+ if self.total_size > 1 and not (accelerator.is_fsdp2 or accelerator.multi_device):
275
+ raise ValueError(
276
+ f"ParallelismConfig is only compatible DistributedType.FSDP (version 2) or DistributedType.Multi{{Device}}, but got {accelerator.distributed_type}."
277
+ )
278
+
279
+ for parallelism, size in self._sizes.items():
280
+ if size == 1 and getattr(self, f"{parallelism}_handler", None) is not None:
281
+ _warnings.add(
282
+ f"ParallelismConfig.{parallelism}_handler is set, but {parallelism}_size is set to 1. This handler will be ignored."
283
+ )
284
+
285
+ if _warnings and accelerator.is_main_process:
286
+ warnings.warn(
287
+ "ParallelismConfig has the following warnings:\n" + "\n".join(_warnings),
288
+ UserWarning,
289
+ )
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/scheduler.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation
16
+
17
+ import warnings
18
+
19
+ from .state import AcceleratorState, GradientState
20
+
21
+
22
+ warnings.filterwarnings("ignore", category=UserWarning, module="torch.optim.lr_scheduler")
23
+
24
+
25
+ class AcceleratedScheduler:
26
+ """
27
+ A wrapper around a learning rate scheduler that will only step when the optimizer(s) have a training step. Useful
28
+ to avoid making a scheduler step too fast when gradients went overflow and there was no training step (in mixed
29
+ precision training)
30
+
31
+ When performing gradient accumulation scheduler lengths should not be changed accordingly, Accelerate will always
32
+ step the scheduler to account for it.
33
+
34
+ Args:
35
+ scheduler (`torch.optim.lr_scheduler._LRScheduler`):
36
+ The scheduler to wrap.
37
+ optimizers (one or a list of `torch.optim.Optimizer`):
38
+ The optimizers used.
39
+ step_with_optimizer (`bool`, *optional*, defaults to `True`):
40
+ Whether or not the scheduler should be stepped at each optimizer step.
41
+ split_batches (`bool`, *optional*, defaults to `False`):
42
+ Whether or not the dataloaders split one batch across the different processes (so batch size is the same
43
+ regardless of the number of processes) or create batches on each process (so batch size is the original
44
+ batch size multiplied by the number of processes).
45
+ """
46
+
47
+ def __init__(self, scheduler, optimizers, step_with_optimizer: bool = True, split_batches: bool = False):
48
+ self.scheduler = scheduler
49
+ self.optimizers = optimizers if isinstance(optimizers, (list, tuple)) else [optimizers]
50
+ self.split_batches = split_batches
51
+ self.step_with_optimizer = step_with_optimizer
52
+ self.gradient_state = GradientState()
53
+
54
+ def step(self, *args, **kwargs):
55
+ if not self.step_with_optimizer:
56
+ # No link between scheduler and optimizer -> just step
57
+ self.scheduler.step(*args, **kwargs)
58
+ return
59
+
60
+ # Otherwise, first make sure the optimizer was stepped.
61
+ if not self.gradient_state.sync_gradients:
62
+ if self.gradient_state.adjust_scheduler:
63
+ self.scheduler._step_count += 1
64
+ return
65
+
66
+ for opt in self.optimizers:
67
+ if opt.step_was_skipped:
68
+ return
69
+ if self.split_batches:
70
+ # Split batches -> the training dataloader batch size is not changed so one step per training step
71
+ self.scheduler.step(*args, **kwargs)
72
+ else:
73
+ # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do
74
+ # num_processes steps per training step
75
+ num_processes = AcceleratorState().num_processes
76
+ for _ in range(num_processes):
77
+ # Special case when using OneCycle and `drop_last` was not used
78
+ if hasattr(self.scheduler, "total_steps"):
79
+ if self.scheduler._step_count <= self.scheduler.total_steps:
80
+ self.scheduler.step(*args, **kwargs)
81
+ else:
82
+ self.scheduler.step(*args, **kwargs)
83
+
84
+ # Passthroughs
85
+ def get_last_lr(self):
86
+ return self.scheduler.get_last_lr()
87
+
88
+ def state_dict(self):
89
+ return self.scheduler.state_dict()
90
+
91
+ def load_state_dict(self, state_dict):
92
+ self.scheduler.load_state_dict(state_dict)
93
+
94
+ def get_lr(self):
95
+ return self.scheduler.get_lr()
96
+
97
+ def print_lr(self, *args, **kwargs):
98
+ return self.scheduler.print_lr(*args, **kwargs)
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/state.py ADDED
@@ -0,0 +1,1369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ import logging
18
+ import os
19
+ import threading
20
+ import warnings
21
+ import weakref
22
+ from contextlib import contextmanager
23
+ from functools import partial
24
+ from typing import Any, Callable
25
+
26
+ import torch
27
+
28
+ from .utils import (
29
+ DistributedType,
30
+ DynamoBackend,
31
+ GradientAccumulationPlugin,
32
+ check_cuda_fp8_capability,
33
+ check_cuda_p2p_ib_support,
34
+ deepspeed_required,
35
+ get_cpu_distributed_information,
36
+ get_int_from_env,
37
+ is_ccl_available,
38
+ is_datasets_available,
39
+ is_deepspeed_available,
40
+ is_fp8_available,
41
+ is_habana_gaudi1,
42
+ is_hpu_available,
43
+ is_ipex_available,
44
+ is_mlu_available,
45
+ is_mps_available,
46
+ is_musa_available,
47
+ is_npu_available,
48
+ is_sdaa_available,
49
+ is_torch_xla_available,
50
+ is_xccl_available,
51
+ is_xpu_available,
52
+ parse_choice_from_env,
53
+ parse_flag_from_env,
54
+ set_numa_affinity,
55
+ )
56
+ from .utils.dataclasses import SageMakerDistributedType
57
+
58
+
59
+ if is_torch_xla_available():
60
+ import torch_xla.core.xla_model as xm
61
+ import torch_xla.runtime as xr
62
+
63
+ if is_mlu_available(check_device=False):
64
+ import torch_mlu # noqa: F401
65
+
66
+ if is_sdaa_available(check_device=False):
67
+ import torch_sdaa # noqa: F401
68
+
69
+ if is_musa_available(check_device=False):
70
+ import torch_musa # noqa: F401
71
+
72
+ if is_npu_available(check_device=False):
73
+ import torch_npu # noqa: F401
74
+
75
+
76
+ logger = logging.getLogger(__name__)
77
+
78
+
79
+ def is_initialized() -> bool:
80
+ """
81
+ Checks if the `AcceleratorState` has been initialized from `Accelerator`. Same as `AcceleratorState.initialized`,
82
+ but works as a module method.
83
+ """
84
+ return AcceleratorState._shared_state != {}
85
+
86
+
87
+ # Lambda function that does nothing
88
+ def do_nothing(*args, **kwargs):
89
+ return None
90
+
91
+
92
+ class ThreadLocalSharedDict(threading.local):
93
+ """
94
+ Descriptor that holds a dict shared between instances of a class in the same thread.
95
+
96
+ Note: Descriptors have slightly different semantics than just a dict field on its own.
97
+ `PartialState(...)._shared_state` and `PartialState._shared_state` (instance vs class) give the same value: the
98
+ underlying _storage dict. Likewise, `PartialState(...)._shared_state = {...}` overrides the _storage dict inside
99
+ the descriptor as you would expect. However, `PartialState._shared_state = {}` actually replaces the descriptor
100
+ object with a dict instead Thus, you should modify the _storage dict in-place (e.g. `_shared_state.clear()`).
101
+
102
+ See Python documentation for an explanation of descriptors: https://docs.python.org/3/howto/descriptor.html
103
+
104
+ This is required for using PyTorch/XLA with PJRT in multithreaded mode (required for TPU v2 and v3).
105
+
106
+ See https://github.com/pytorch/xla/blob/r2.0/docs/pjrt.md#multithreading-on-tpu-v2v3
107
+ """
108
+
109
+ def __init__(self, thread_local: bool = False):
110
+ self._storage = {}
111
+
112
+ def __get__(self, obj, objtype=None):
113
+ return self._storage
114
+
115
+ def __set__(self, obj, value):
116
+ self._storage = value
117
+
118
+
119
+ # Prefer global shared dictionary, except when using TPU.
120
+ SharedDict = dict if not is_torch_xla_available() else ThreadLocalSharedDict
121
+
122
+
123
+ # Inspired by Alex Martelli's 'Borg'.
124
+ class PartialState:
125
+ """
126
+ Singleton class that has information about the current training environment and functions to help with process
127
+ control. Designed to be used when only process control and device execution states are needed. Does *not* need to
128
+ be initialized from `Accelerator`.
129
+
130
+ Args:
131
+ cpu (`bool`, *optional*):
132
+ Whether or not to force the script to execute on CPU. Will ignore any accelerators available if set to
133
+ `True` and force the execution on the CPU.
134
+ kwargs (additional keyword arguments, *optional*):
135
+ Additional keyword arguments to pass to the relevant `init_process_group` function. Valid `kwargs` can be
136
+ found in [`utils.InitProcessGroupKwargs`]. See the example section for detailed usage.
137
+
138
+ **Available attributes:**
139
+
140
+ - **device** (`torch.device`) -- The device to use.
141
+ - **distributed_type** ([`~accelerate.state.DistributedType`]) -- The type of distributed environment currently
142
+ in use.
143
+ - **local_process_index** (`int`) -- The index of the current process on the current server.
144
+ - **mixed_precision** (`str`) -- Whether or not the current script will use mixed precision, and if so the type
145
+ of mixed precision being performed. (Choose from 'no','fp16','bf16 or 'fp8').
146
+ - **num_processes** (`int`) -- The number of processes currently launched in parallel.
147
+ - **process_index** (`int`) -- The index of the current process.
148
+ - **is_last_process** (`bool`) -- Whether or not the current process is the last one.
149
+ - **is_main_process** (`bool`) -- Whether or not the current process is the main one.
150
+ - **is_local_main_process** (`bool`) -- Whether or not the current process is the main one on the local node.
151
+ - **debug** (`bool`) -- Whether or not the current script is being run in debug mode.
152
+
153
+ Example:
154
+ ```python
155
+ from accelerate.utils import InitProcessGroupKwargs
156
+
157
+ # To include `InitProcessGroupKwargs`, init then call `.to_kwargs()`
158
+ kwargs = InitProcessGroupKwargs(...).to_kwargs()
159
+ state = PartialState(**kwargs)
160
+ ```
161
+ """
162
+
163
+ _shared_state = SharedDict()
164
+ _known_attrs = [
165
+ "_cpu",
166
+ "_mixed_precision",
167
+ "_shared_state",
168
+ "backend",
169
+ "debug",
170
+ "device",
171
+ "distributed_type",
172
+ "fork_launched",
173
+ "local_process_index",
174
+ "num_processes",
175
+ "process_index",
176
+ ]
177
+
178
+ def __init__(self, cpu: bool = False, **kwargs):
179
+ self.__dict__ = self._shared_state
180
+ if not self.initialized:
181
+ self._cpu = cpu
182
+ self.backend = None
183
+ self.parallelism_config = kwargs.pop("parallelism_config", None)
184
+ self.device_mesh = kwargs.pop("device_mesh", None)
185
+ env_device = os.environ.get("ACCELERATE_TORCH_DEVICE", None)
186
+ self.device = torch.device(env_device) if env_device is not None else None
187
+ self.debug = parse_flag_from_env("ACCELERATE_DEBUG_MODE")
188
+ use_sagemaker_dp = kwargs.pop("_use_sagemaker_dp", None)
189
+ dist_information = None
190
+ if use_sagemaker_dp is None:
191
+ use_sagemaker_dp = (
192
+ os.environ.get("ACCELERATE_USE_SAGEMAKER", "false").lower() == "true"
193
+ and os.environ.get("ACCELERATE_SAGEMAKER_DISTRIBUTED_TYPE") != SageMakerDistributedType.NO
194
+ )
195
+
196
+ # Sets up self.backend + imports
197
+ original_backend = kwargs.pop("backend", None)
198
+ backend, distributed_type = self._prepare_backend(cpu, use_sagemaker_dp, original_backend)
199
+ if original_backend is not None and backend != original_backend:
200
+ raise ValueError(f"Your assigned backend {original_backend} is not avaliable, please use {backend}")
201
+ self.backend = backend
202
+ self.distributed_type = distributed_type
203
+ use_deepspeed = False
204
+ if not cpu and self.backend != "xla":
205
+ if int(os.environ.get("LOCAL_RANK", -1)) != -1:
206
+ # Deal with spawning deepspeed
207
+ if os.environ.get("ACCELERATE_USE_DEEPSPEED", "false").lower() == "true":
208
+ if not is_deepspeed_available():
209
+ raise ImportError(
210
+ "DeepSpeed is not available => install it using `pip3 install deepspeed` or build it from source"
211
+ )
212
+ from deepspeed import comm as dist
213
+
214
+ if not dist.is_initialized():
215
+ if self.backend == "tccl":
216
+ local_rank = os.environ.get("LOCAL_RANK", -1)
217
+ torch.sdaa.set_device(f"sdaa:{local_rank}")
218
+ dist.init_distributed(dist_backend=self.backend, auto_mpi_discovery=False, **kwargs)
219
+ # We need to flag to `use_deepspeed` to be True to override `distributed_type` later
220
+ use_deepspeed = True
221
+ # Deal with all other backends but XPU and CPU, that gets handled special later
222
+ elif (
223
+ self.distributed_type not in (DistributedType.MULTI_XPU, DistributedType.MULTI_CPU)
224
+ and not torch.distributed.is_initialized()
225
+ ):
226
+ if self.backend == "tccl":
227
+ local_rank = os.environ.get("LOCAL_RANK", -1)
228
+ torch.sdaa.set_device(f"sdaa:{local_rank}")
229
+ if (
230
+ self.backend == "nccl"
231
+ and os.environ.get("ACCELERATE_USE_FSDP", "false").lower() == "true"
232
+ and (
233
+ os.environ.get("FSDP_OFFLOAD_PARAMS", "false").lower() == "true"
234
+ or os.environ.get("FSDP_STATE_DICT_TYPE", "SHARDED_STATE_DICT") == "FULL_STATE_DICT"
235
+ )
236
+ ):
237
+ self.backend = "cuda:nccl,cpu:gloo"
238
+ torch.distributed.init_process_group(backend=self.backend, **kwargs)
239
+
240
+ # XPU and CPU require special env configs to be set
241
+ if self.distributed_type in (DistributedType.MULTI_XPU, DistributedType.MULTI_CPU):
242
+ dist_information = get_cpu_distributed_information()
243
+ os.environ["RANK"] = str(dist_information.rank)
244
+ os.environ["WORLD_SIZE"] = str(dist_information.world_size)
245
+ os.environ["LOCAL_RANK"] = str(dist_information.local_rank)
246
+ os.environ["LOCAL_WORLD_SIZE"] = str(dist_information.local_world_size)
247
+ if not os.environ.get("MASTER_PORT", None):
248
+ os.environ["MASTER_PORT"] = "29500"
249
+ if (
250
+ not os.environ.get("MASTER_ADDR", None)
251
+ and dist_information.local_world_size != dist_information.world_size
252
+ and self.backend != "mpi"
253
+ ):
254
+ raise ValueError(
255
+ "Tried to launch on distributed with multinode, but `MASTER_ADDR` env was not set, "
256
+ "please try exporting rank 0's hostname as `MASTER_ADDR`"
257
+ )
258
+ kwargs["rank"] = dist_information.rank
259
+ kwargs["world_size"] = dist_information.world_size
260
+
261
+ if (
262
+ self.distributed_type == DistributedType.MULTI_CPU
263
+ and get_int_from_env(["OMP_NUM_THREADS"], 0) == 0
264
+ ):
265
+ import psutil
266
+
267
+ num_cpu_threads_per_process = int(
268
+ psutil.cpu_count(logical=False) / dist_information.local_world_size
269
+ )
270
+ if num_cpu_threads_per_process == 0:
271
+ num_cpu_threads_per_process = 1
272
+ torch.set_num_threads(num_cpu_threads_per_process)
273
+ warnings.warn(
274
+ f"OMP_NUM_THREADS/MKL_NUM_THREADS unset, we set it at {num_cpu_threads_per_process} to improve oob"
275
+ " performance."
276
+ )
277
+
278
+ if not torch.distributed.is_initialized():
279
+ torch.distributed.init_process_group(backend=self.backend, **kwargs)
280
+
281
+ # No backend == no distributed training
282
+ if self.backend is None:
283
+ self.distributed_type = DistributedType.NO
284
+ self.num_processes = 1
285
+ self.process_index = 0
286
+ self.local_process_index = 0
287
+ elif self.backend == "xla":
288
+ # XLA needs device setting first for `set_replication`
289
+ self.set_device()
290
+ xm.set_replication(self.device, xm.get_xla_supported_devices())
291
+ self.num_processes = xr.world_size()
292
+ self.process_index = xr.global_ordinal()
293
+ if is_torch_xla_available(check_is_tpu=True):
294
+ self.local_process_index = xm.get_local_ordinal()
295
+ else:
296
+ self.local_process_index = int(os.environ.get("LOCAL_RANK", -1))
297
+ else:
298
+ self.num_processes = torch.distributed.get_world_size()
299
+ self.process_index = torch.distributed.get_rank()
300
+ self.local_process_index = (
301
+ int(os.environ.get("LOCAL_RANK", -1)) if dist_information is None else dist_information.local_rank
302
+ )
303
+ self.set_device()
304
+ # Now we can change to deepseed
305
+ if use_deepspeed:
306
+ self.distributed_type = DistributedType.DEEPSPEED
307
+
308
+ # Set CPU affinity if enabled
309
+ if parse_flag_from_env("ACCELERATE_CPU_AFFINITY", False):
310
+ set_numa_affinity(self.local_process_index)
311
+
312
+ # Check for old RTX 4000's that can't use P2P or IB and are on old drivers
313
+ if self.device.type == "cuda" and not check_cuda_p2p_ib_support():
314
+ if "NCCL_P2P_DISABLE" not in os.environ or "NCCL_IB_DISABLE" not in os.environ:
315
+ raise NotImplementedError(
316
+ "Using RTX 4000 series doesn't support faster communication broadband via P2P or IB. "
317
+ 'Please set `NCCL_P2P_DISABLE="1"` and `NCCL_IB_DISABLE="1" or use `accelerate launch` which '
318
+ "will do this automatically."
319
+ )
320
+
321
+ # Important: This should be the *only* code outside of `self.initialized!`
322
+ self.fork_launched = parse_flag_from_env("FORK_LAUNCHED", 0)
323
+
324
+ def __repr__(self) -> str:
325
+ return (
326
+ f"Distributed environment: {self.distributed_type}{(' Backend: ' + self.backend) if self.backend else ''}\n"
327
+ f"Num processes: {self.num_processes}\n"
328
+ f"Process index: {self.process_index}\n"
329
+ f"Local process index: {self.local_process_index}\n"
330
+ f"Device: {self.device}\n"
331
+ )
332
+
333
+ @staticmethod
334
+ def _reset_state():
335
+ "Resets `_shared_state`, is used internally and should not be called"
336
+ PartialState._shared_state.clear()
337
+
338
+ @property
339
+ def initialized(self) -> bool:
340
+ "Returns whether the `PartialState` has been initialized"
341
+ return self._shared_state != {}
342
+
343
+ @property
344
+ def use_distributed(self):
345
+ """
346
+ Whether the Accelerator is configured for distributed training
347
+ """
348
+ return self.distributed_type != DistributedType.NO and self.num_processes > 1
349
+
350
+ @property
351
+ def is_last_process(self) -> bool:
352
+ "Returns whether the current process is the last one"
353
+ return self.process_index == self.num_processes - 1
354
+
355
+ @property
356
+ def is_main_process(self) -> bool:
357
+ "Returns whether the current process is the main process"
358
+ return (
359
+ self.process_index == 0 if self.distributed_type != DistributedType.MEGATRON_LM else self.is_last_process
360
+ )
361
+
362
+ @property
363
+ def is_local_main_process(self) -> bool:
364
+ "Returns whether the current process is the main process on the local node"
365
+ return (
366
+ self.local_process_index == 0
367
+ if self.distributed_type != DistributedType.MEGATRON_LM
368
+ else self.is_last_process
369
+ )
370
+
371
+ def wait_for_everyone(self):
372
+ """
373
+ Will stop the execution of the current process until every other process has reached that point (so this does
374
+ nothing when the script is only run in one process). Useful to do before saving a model.
375
+
376
+ Example:
377
+
378
+ ```python
379
+ >>> # Assuming two GPU processes
380
+ >>> import time
381
+ >>> from accelerate.state import PartialState
382
+
383
+ >>> state = PartialState()
384
+ >>> if state.is_main_process:
385
+ ... time.sleep(2)
386
+ >>> else:
387
+ ... print("I'm waiting for the main process to finish its sleep...")
388
+ >>> state.wait_for_everyone()
389
+ >>> # Should print on every process at the same time
390
+ >>> print("Everyone is here")
391
+ ```
392
+ """
393
+ if self.distributed_type in (
394
+ DistributedType.MULTI_GPU,
395
+ DistributedType.MULTI_MLU,
396
+ DistributedType.MULTI_SDAA,
397
+ DistributedType.MULTI_MUSA,
398
+ DistributedType.MULTI_NPU,
399
+ DistributedType.MULTI_XPU,
400
+ DistributedType.MULTI_CPU,
401
+ DistributedType.MULTI_HPU,
402
+ DistributedType.DEEPSPEED,
403
+ DistributedType.FSDP,
404
+ ):
405
+ torch.distributed.barrier()
406
+ elif self.distributed_type == DistributedType.XLA:
407
+ xm.rendezvous("accelerate.utils.wait_for_everyone")
408
+
409
+ def _goes_first(self, is_main: bool):
410
+ if not is_main:
411
+ self.wait_for_everyone()
412
+
413
+ yield
414
+
415
+ if is_main:
416
+ self.wait_for_everyone()
417
+
418
+ @contextmanager
419
+ def split_between_processes(self, inputs: list | tuple | dict | torch.Tensor, apply_padding: bool = False):
420
+ """
421
+ Splits `input` between `self.num_processes` quickly and can be then used on that process. Useful when doing
422
+ distributed inference, such as with different prompts.
423
+
424
+ Note that when using a `dict`, all keys need to have the same number of elements.
425
+
426
+ Args:
427
+ inputs (`list`, `tuple`, `torch.Tensor`, `dict` of `list`/`tuple`/`torch.Tensor`, or `datasets.Dataset`):
428
+ The input to split between processes.
429
+ apply_padding (`bool`, `optional`, defaults to `False`):
430
+ Whether to apply padding by repeating the last element of the input so that all processes have the same
431
+ number of elements. Useful when trying to perform actions such as `gather()` on the outputs or passing
432
+ in less inputs than there are processes. If so, just remember to drop the padded elements afterwards.
433
+
434
+
435
+ Example:
436
+
437
+ ```python
438
+ # Assume there are two processes
439
+ from accelerate import PartialState
440
+
441
+ state = PartialState()
442
+ with state.split_between_processes(["A", "B", "C"]) as inputs:
443
+ print(inputs)
444
+ # Process 0
445
+ ["A", "B"]
446
+ # Process 1
447
+ ["C"]
448
+
449
+ with state.split_between_processes(["A", "B", "C"], apply_padding=True) as inputs:
450
+ print(inputs)
451
+ # Process 0
452
+ ["A", "B"]
453
+ # Process 1
454
+ ["C", "C"]
455
+ ```
456
+ """
457
+ if self.num_processes == 1:
458
+ yield inputs
459
+ return
460
+ length = len(inputs)
461
+ # Nested dictionary of any types
462
+ if isinstance(inputs, dict):
463
+ length = len(inputs[list(inputs.keys())[0]])
464
+ if not all(len(v) == length for v in inputs.values()):
465
+ raise ValueError("All values in the dictionary must have the same length")
466
+ num_samples_per_process, num_extras = divmod(length, self.num_processes)
467
+ start_index = self.process_index * num_samples_per_process + min(self.process_index, num_extras)
468
+ end_index = start_index + num_samples_per_process + (1 if self.process_index < num_extras else 0)
469
+
470
+ def _split_values(inputs, start_index, end_index):
471
+ if isinstance(inputs, (list, tuple, torch.Tensor)):
472
+ if start_index >= len(inputs):
473
+ result = inputs[-1:]
474
+ else:
475
+ result = inputs[start_index:end_index]
476
+ if apply_padding:
477
+ if isinstance(result, torch.Tensor):
478
+ from accelerate.utils import pad_across_processes, send_to_device
479
+
480
+ # The tensor needs to be on the device before we can pad it
481
+ tensorized_result = send_to_device(result, self.device)
482
+ result = pad_across_processes(tensorized_result, pad_index=inputs[-1])
483
+ else:
484
+ result += [result[-1]] * (num_samples_per_process + (1 if num_extras > 0 else 0) - len(result))
485
+ return result
486
+ elif isinstance(inputs, dict):
487
+ for key in inputs.keys():
488
+ inputs[key] = _split_values(inputs[key], start_index, end_index)
489
+ return inputs
490
+ else:
491
+ if is_datasets_available():
492
+ from datasets import Dataset
493
+
494
+ if isinstance(inputs, Dataset):
495
+ if start_index >= len(inputs):
496
+ start_index = len(inputs) - 1
497
+ if end_index > len(inputs):
498
+ end_index = len(inputs)
499
+ result_idcs = list(range(start_index, end_index))
500
+ if apply_padding:
501
+ result_idcs += [end_index - 1] * (
502
+ num_samples_per_process + (1 if num_extras > 0 else 0) - len(result_idcs)
503
+ )
504
+ return inputs.select(result_idcs)
505
+ return inputs
506
+
507
+ yield _split_values(inputs, start_index, end_index)
508
+
509
+ @contextmanager
510
+ def main_process_first(self):
511
+ """
512
+ Lets the main process go first inside a with block.
513
+
514
+ The other processes will enter the with block after the main process exits.
515
+
516
+ Example:
517
+
518
+ ```python
519
+ >>> from accelerate import Accelerator
520
+
521
+ >>> accelerator = Accelerator()
522
+ >>> with accelerator.main_process_first():
523
+ ... # This will be printed first by process 0 then in a seemingly
524
+ ... # random order by the other processes.
525
+ ... print(f"This will be printed by process {accelerator.process_index}")
526
+ ```
527
+ """
528
+ yield from self._goes_first(self.is_main_process)
529
+
530
+ @contextmanager
531
+ def local_main_process_first(self):
532
+ """
533
+ Lets the local main process go inside a with block.
534
+
535
+ The other processes will enter the with block after the main process exits.
536
+
537
+ Example:
538
+
539
+ ```python
540
+ >>> from accelerate.state import PartialState
541
+
542
+ >>> state = PartialState()
543
+ >>> with state.local_main_process_first():
544
+ ... # This will be printed first by local process 0 then in a seemingly
545
+ ... # random order by the other processes.
546
+ ... print(f"This will be printed by process {state.local_process_index}")
547
+ ```
548
+ """
549
+ yield from self._goes_first(self.is_local_main_process)
550
+
551
+ def on_main_process(self, function: Callable[..., Any] = None):
552
+ """
553
+ Decorator that only runs the decorated function on the main process.
554
+
555
+ Args:
556
+ function (`Callable`): The function to decorate.
557
+
558
+ Example:
559
+
560
+ ```python
561
+ >>> from accelerate.state import PartialState
562
+
563
+ >>> state = PartialState()
564
+
565
+
566
+ >>> @state.on_main_process
567
+ ... def print_something():
568
+ ... print("This will be printed by process 0 only.")
569
+
570
+
571
+ >>> print_something()
572
+ "This will be printed by process 0 only"
573
+ ```
574
+ """
575
+ if not self.initialized:
576
+ raise ValueError("The `PartialState` or `Accelerator` must be initialized before calling this function.")
577
+ if self.is_main_process or not self.use_distributed:
578
+ return function
579
+ return do_nothing
580
+
581
+ def on_local_main_process(self, function: Callable[..., Any] = None):
582
+ """
583
+ Decorator that only runs the decorated function on the local main process.
584
+
585
+ Args:
586
+ function (`Callable`): The function to decorate.
587
+
588
+ Example:
589
+ ```python
590
+ # Assume we have 2 servers with 4 processes each.
591
+ from accelerate.state import PartialState
592
+
593
+ state = PartialState()
594
+
595
+
596
+ @state.on_local_main_process
597
+ def print_something():
598
+ print("This will be printed by process 0 only on each server.")
599
+
600
+
601
+ print_something()
602
+ # On server 1:
603
+ "This will be printed by process 0 only"
604
+ # On server 2:
605
+ "This will be printed by process 0 only"
606
+ ```
607
+ """
608
+ if self.is_local_main_process or not self.use_distributed:
609
+ return function
610
+ return do_nothing
611
+
612
+ def on_last_process(self, function: Callable[..., Any]):
613
+ """
614
+ Decorator that only runs the decorated function on the last process.
615
+
616
+ Args:
617
+ function (`Callable`): The function to decorate.
618
+
619
+ Example:
620
+ ```python
621
+ # Assume we have 4 processes.
622
+ from accelerate.state import PartialState
623
+
624
+ state = PartialState()
625
+
626
+
627
+ @state.on_last_process
628
+ def print_something():
629
+ print(f"Printed on process {state.process_index}")
630
+
631
+
632
+ print_something()
633
+ "Printed on process 3"
634
+ ```
635
+ """
636
+ if self.is_last_process or not self.use_distributed:
637
+ return function
638
+ return do_nothing
639
+
640
+ def on_process(self, function: Callable[..., Any] = None, process_index: int = None):
641
+ """
642
+ Decorator that only runs the decorated function on the process with the given index.
643
+
644
+ Args:
645
+ function (`Callable`, `optional`):
646
+ The function to decorate.
647
+ process_index (`int`, `optional`):
648
+ The index of the process on which to run the function.
649
+
650
+ Example:
651
+ ```python
652
+ # Assume we have 4 processes.
653
+ from accelerate.state import PartialState
654
+
655
+ state = PartialState()
656
+
657
+
658
+ @state.on_process(process_index=2)
659
+ def print_something():
660
+ print(f"Printed on process {state.process_index}")
661
+
662
+
663
+ print_something()
664
+ "Printed on process 2"
665
+ ```
666
+ """
667
+ if function is None:
668
+ return partial(self.on_process, process_index=process_index)
669
+ if (self.process_index == process_index) or (not self.use_distributed):
670
+ return function
671
+ return do_nothing
672
+
673
+ def on_local_process(self, function: Callable[..., Any] = None, local_process_index: int = None):
674
+ """
675
+ Decorator that only runs the decorated function on the process with the given index on the current node.
676
+
677
+ Args:
678
+ function (`Callable`, *optional*):
679
+ The function to decorate.
680
+ local_process_index (`int`, *optional*):
681
+ The index of the local process on which to run the function.
682
+
683
+ Example:
684
+ ```python
685
+ # Assume we have 2 servers with 4 processes each.
686
+ from accelerate import Accelerator
687
+
688
+ accelerator = Accelerator()
689
+
690
+
691
+ @accelerator.on_local_process(local_process_index=2)
692
+ def print_something():
693
+ print(f"Printed on process {accelerator.local_process_index}")
694
+
695
+
696
+ print_something()
697
+ # On server 1:
698
+ "Printed on process 2"
699
+ # On server 2:
700
+ "Printed on process 2"
701
+ ```
702
+ """
703
+ if function is None:
704
+ return partial(self.on_local_process, local_process_index=local_process_index)
705
+ if (self.local_process_index == local_process_index) or (not self.use_distributed):
706
+ return function
707
+ return do_nothing
708
+
709
+ def print(self, *args, **kwargs):
710
+ if self.is_local_main_process:
711
+ print(*args, **kwargs)
712
+
713
+ @property
714
+ def default_device(self) -> torch.device:
715
+ """
716
+ Returns the default device which is:
717
+ - MPS if `torch.backends.mps.is_available()` and `torch.backends.mps.is_built()` both return True.
718
+ - CUDA if `torch.cuda.is_available()`
719
+ - MLU if `is_mlu_available()`
720
+ - SDAA if `is_sdaa_available()`
721
+ - MUSA if `is_musa_available()`
722
+ - NPU if `is_npu_available()`
723
+ - HPU if `is_hpu_available()`
724
+ - CPU otherwise
725
+ """
726
+ if is_mps_available():
727
+ os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
728
+ return torch.device("mps")
729
+ elif is_mlu_available():
730
+ return torch.device("mlu")
731
+ elif is_sdaa_available():
732
+ return torch.device("sdaa")
733
+ elif is_musa_available():
734
+ return torch.device("musa")
735
+ # NPU should be checked before CUDA when using `transfer_to_npu`
736
+ # See issue #3020: https://github.com/huggingface/accelerate/issues/3020
737
+ elif is_npu_available():
738
+ return torch.device("npu")
739
+ elif is_hpu_available():
740
+ return torch.device("hpu")
741
+ elif torch.cuda.is_available():
742
+ return torch.device("cuda")
743
+ elif is_xpu_available():
744
+ return torch.device("xpu")
745
+ else:
746
+ return torch.device("cpu")
747
+
748
+ def _prepare_backend(
749
+ self, cpu: bool = False, sagemaker_dp=False, backend: str = None
750
+ ) -> tuple[str, DistributedType]:
751
+ "Prepares any imports needed before initializing the distributed backend and sets `self.backend` properly"
752
+ distributed_type = None
753
+ if sagemaker_dp:
754
+ import smdistributed.dataparallel.torch.torch_smddp # noqa
755
+
756
+ backend = "smddp"
757
+ distributed_type = DistributedType.MULTI_GPU
758
+ elif is_torch_xla_available():
759
+ backend = "xla"
760
+ distributed_type = DistributedType.XLA
761
+
762
+ elif int(os.environ.get("LOCAL_RANK", -1)) != -1 and not cpu:
763
+ if is_mlu_available():
764
+ backend = "cncl"
765
+ distributed_type = DistributedType.MULTI_MLU
766
+ if is_sdaa_available():
767
+ backend = "tccl"
768
+ distributed_type = DistributedType.MULTI_SDAA
769
+ elif is_musa_available():
770
+ backend = "mccl"
771
+ distributed_type = DistributedType.MULTI_MUSA
772
+ # NPU should be checked before CUDA when using `transfer_to_npu`
773
+ # See issue #3020: https://github.com/huggingface/accelerate/issues/3020
774
+ elif is_npu_available():
775
+ backend = "hccl"
776
+ distributed_type = DistributedType.MULTI_NPU
777
+ elif is_hpu_available(init_hccl=True):
778
+ if backend is None:
779
+ backend = "hccl"
780
+ distributed_type = DistributedType.MULTI_HPU
781
+ elif torch.cuda.is_available():
782
+ if backend is None:
783
+ backend = "nccl"
784
+ distributed_type = DistributedType.MULTI_GPU
785
+ elif is_xpu_available() and is_xccl_available():
786
+ if backend is None:
787
+ backend = "xccl"
788
+ distributed_type = DistributedType.MULTI_XPU
789
+
790
+ if distributed_type is None and (
791
+ int(os.environ.get("LOCAL_RANK", -1)) != -1
792
+ or get_int_from_env(["PMI_SIZE", "OMPI_COMM_WORLD_SIZE", "MV2_COMM_WORLD_SIZE", "WORLD_SIZE"], 1) > 1
793
+ ):
794
+ if not cpu and is_xpu_available():
795
+ distributed_type = DistributedType.MULTI_XPU
796
+ else:
797
+ distributed_type = DistributedType.MULTI_CPU
798
+
799
+ if (
800
+ backend in (None, "ccl")
801
+ and is_ccl_available()
802
+ and (get_int_from_env(["CCL_WORKER_COUNT"], 0) > 0 or distributed_type == DistributedType.MULTI_XPU)
803
+ ):
804
+ import oneccl_bindings_for_pytorch # noqa: F401
805
+
806
+ backend = "ccl"
807
+ elif backend in (None, "mpi") and torch.distributed.is_mpi_available():
808
+ backend = "mpi"
809
+ else:
810
+ backend = "gloo"
811
+ if distributed_type is None:
812
+ distributed_type = DistributedType.NO
813
+
814
+ return backend, distributed_type
815
+
816
+ def set_device(self):
817
+ """
818
+ Sets the device in `self.device` to the current distributed environment.
819
+ """
820
+ if self.device is not None:
821
+ return
822
+ if self.distributed_type == DistributedType.NO:
823
+ self.device = torch.device("cpu") if self._cpu else self.default_device
824
+ return
825
+ device = str(self.distributed_type).split(".")[-1].replace("MULTI_", "").lower()
826
+ if device not in ("cpu", "gpu", "mlu", "musa", "npu", "xpu", "xla", "hpu", "sdaa"):
827
+ raise ValueError(
828
+ f"Can't set device for {self.distributed_type} ({device}), verify we should be calling `_set_device()` for it!"
829
+ )
830
+ if device == "xla":
831
+ self.device = xm.xla_device()
832
+ elif device == "hpu":
833
+ self.device = torch.device("hpu", torch.hpu.current_device())
834
+ else:
835
+ if device == "gpu":
836
+ device = "cuda"
837
+ device_module = getattr(torch, device)
838
+ device_index = self.local_process_index % device_module.device_count()
839
+ self.device = torch.device(device, device_index)
840
+ device_module.set_device(self.device)
841
+
842
+ def destroy_process_group(self, group=None):
843
+ """
844
+ Destroys the process group. If one is not specified, the default process group is destroyed.
845
+ """
846
+ if self.fork_launched and group is None:
847
+ return
848
+ # needed when using torch.distributed.init_process_group
849
+ if torch.distributed.is_initialized():
850
+ torch.distributed.destroy_process_group(group)
851
+
852
+ def __getattr__(self, name: str):
853
+ # By this point we know that no attributes of `self` contain `name`,
854
+ # so we just modify the error message
855
+ if name in self._known_attrs:
856
+ raise AttributeError(
857
+ f"`PartialState` object has no attribute `{name}`. "
858
+ "This happens if `PartialState._reset_state()` was called and "
859
+ "an `Accelerator` or `PartialState` was not reinitialized."
860
+ )
861
+ # Raise a typical AttributeError
862
+ raise AttributeError(f"'PartialState' object has no attribute '{name}'")
863
+
864
+
865
+ class AcceleratorState:
866
+ """
867
+ Singleton class that has information about the current training environment.
868
+
869
+ **Available attributes:**
870
+
871
+ - **device** (`torch.device`) -- The device to use.
872
+ - **distributed_type** ([`~accelerate.state.DistributedType`]) -- The type of distributed environment currently
873
+ in use.
874
+ - **parallelism_config** ([`~accelerate.utils.ParallelismConfig`]) -- The parallelism configuration for the
875
+ current training environment. This is used to configure the distributed training environment.
876
+ - **initialized** (`bool`) -- Whether or not the `AcceleratorState` has been initialized from `Accelerator`.
877
+ - **local_process_index** (`int`) -- The index of the current process on the current server.
878
+ - **mixed_precision** (`str`) -- Whether or not the current script will use mixed precision, and if so the type
879
+ of mixed precision being performed. (Choose from 'no','fp16','bf16 or 'fp8').
880
+ - **num_processes** (`int`) -- The number of processes currently launched in parallel.
881
+ - **process_index** (`int`) -- The index of the current process.
882
+ - **is_last_process** (`bool`) -- Whether or not the current process is the last one.
883
+ - **is_main_process** (`bool`) -- Whether or not the current process is the main one.
884
+ - **is_local_main_process** (`bool`) -- Whether or not the current process is the main one on the local node.
885
+ - **debug** (`bool`) -- Whether or not the current script is being run in debug mode.
886
+ """
887
+
888
+ _shared_state = SharedDict()
889
+ _known_attrs = PartialState._known_attrs + [
890
+ "deepspeed_plugin",
891
+ "use_ipex",
892
+ "fsdp_plugin",
893
+ "megatron_lm_plugin",
894
+ "dynamo_plugin",
895
+ ]
896
+
897
+ def __init__(
898
+ self,
899
+ mixed_precision: str = None,
900
+ cpu: bool = False,
901
+ dynamo_plugin=None,
902
+ deepspeed_plugin=None,
903
+ fsdp_plugin=None,
904
+ torch_tp_plugin=None,
905
+ megatron_lm_plugin=None,
906
+ parallelism_config=None,
907
+ _from_accelerator: bool = False,
908
+ **kwargs,
909
+ ):
910
+ self.__dict__ = self._shared_state
911
+ if parse_flag_from_env("ACCELERATE_USE_CPU"):
912
+ cpu = True
913
+ if PartialState._shared_state == {}:
914
+ PartialState(cpu, **kwargs)
915
+ self.__dict__.update(PartialState._shared_state)
916
+ self._check_initialized(mixed_precision, cpu)
917
+ if not self.initialized:
918
+ self.deepspeed_plugins = None
919
+ self.use_ipex = None
920
+ self.torch_tp_plugin = torch_tp_plugin
921
+ self.parallelism_config = parallelism_config
922
+ mixed_precision = (
923
+ parse_choice_from_env("ACCELERATE_MIXED_PRECISION", "no")
924
+ if mixed_precision is None
925
+ else mixed_precision.lower()
926
+ )
927
+ if mixed_precision == "fp8":
928
+ # this is confusing, why is is_fp8_available only checks for library availability ?
929
+ if not is_fp8_available():
930
+ raise ValueError(
931
+ "Using `fp8` precision requires `transformer_engine` or `MS-AMP` to be installed."
932
+ )
933
+ elif torch.cuda.is_available() and not check_cuda_fp8_capability():
934
+ logger.warning(
935
+ f"The current device has compute capability of {torch.cuda.get_device_capability()} which is "
936
+ "insufficient for FP8 mixed precision training (requires a GPU Hopper/Ada Lovelace "
937
+ "or higher, compute capability of 8.9 or higher). Will use FP16 instead."
938
+ )
939
+ mixed_precision = "fp16"
940
+ elif is_habana_gaudi1():
941
+ logger.warning(
942
+ "The current HPU device is Gaudi1 which does not support FP8 mixed precision training (requires "
943
+ "Gaudi2 or higher). Will use BF16 instead."
944
+ )
945
+ mixed_precision = "bf16"
946
+
947
+ self.dynamo_plugin = dynamo_plugin
948
+ if not _from_accelerator:
949
+ raise ValueError(
950
+ "Please make sure to properly initialize your accelerator via `accelerator = Accelerator()` "
951
+ "before using any functionality from the `accelerate` library."
952
+ )
953
+ # deepspeed handles mixed_precision using deepspeed_config
954
+ self._mixed_precision = "no" if self.distributed_type == DistributedType.DEEPSPEED else mixed_precision
955
+ if self.distributed_type == DistributedType.XLA and is_torch_xla_available(check_is_tpu=True):
956
+ if mixed_precision == "bf16":
957
+ if os.environ.get("ACCELERATE_DOWNCAST_BF16"):
958
+ os.environ["XLA_USE_BF16"] = str(0)
959
+ os.environ["XLA_DOWNCAST_BF16"] = str(1)
960
+ self.downcast_bfloat = True
961
+ else:
962
+ os.environ["XLA_USE_BF16"] = str(1)
963
+ os.environ["XLA_DOWNCAST_BF16"] = str(0)
964
+ self.downcast_bfloat = False
965
+ elif os.environ.get("ACCELERATE_USE_DEEPSPEED", "false").lower() == "true" and not cpu:
966
+ self.distributed_type = DistributedType.DEEPSPEED
967
+ if not isinstance(deepspeed_plugin, dict):
968
+ deepspeed_plugin.set_mixed_precision(mixed_precision)
969
+ deepspeed_plugin.select(_from_accelerator_state=True)
970
+ else:
971
+ for plugin in deepspeed_plugin.values():
972
+ plugin.set_mixed_precision(mixed_precision)
973
+ # The first plugin passed in is always the active one
974
+ first_plugin = next(iter(deepspeed_plugin.values()))
975
+ first_plugin.select(_from_accelerator_state=True)
976
+ self.deepspeed_plugins = deepspeed_plugin
977
+ elif self.distributed_type in [
978
+ DistributedType.MULTI_GPU,
979
+ DistributedType.MULTI_MLU,
980
+ DistributedType.MULTI_SDAA,
981
+ DistributedType.MULTI_MUSA,
982
+ DistributedType.MULTI_NPU,
983
+ DistributedType.MULTI_XPU,
984
+ DistributedType.MULTI_HPU,
985
+ ]:
986
+ # TODO: Siro - remove when axolotl fixes their side
987
+ if not os.environ.get("ACCELERATE_ALLOW_CP_STANDALONE", "false").lower() == "true":
988
+ if self.parallelism_config and self.parallelism_config.cp_enabled and fsdp_plugin is None:
989
+ raise ValueError(
990
+ "`cp_size > 1` specified in the `parallelism_config`, but no `fsdp_plugin` was provided. We need a `fsdp_plugin` to use context parallelism, as we also shard the model across the device mesh to save more memory"
991
+ )
992
+ if (
993
+ self.parallelism_config is not None
994
+ and self.parallelism_config.cp_enabled
995
+ and fsdp_plugin.fsdp_version == 1
996
+ ):
997
+ raise ValueError(
998
+ "Using `cp_size>1` requires FSDP2, but the provided `fsdp_plugin` is using FSDP1. "
999
+ )
1000
+ if (os.environ.get("ACCELERATE_USE_FSDP", "false").lower() == "true" or fsdp_plugin is not None) or (
1001
+ self.parallelism_config is not None and self.parallelism_config.cp_enabled
1002
+ ):
1003
+ self.distributed_type = DistributedType.FSDP
1004
+ if self._mixed_precision != "no" and fsdp_plugin is not None:
1005
+ fsdp_plugin.set_mixed_precision(self._mixed_precision)
1006
+ self.fsdp_plugin = fsdp_plugin
1007
+ if os.environ.get(
1008
+ "ACCELERATE_USE_MEGATRON_LM", "false"
1009
+ ).lower() == "true" and self.distributed_type not in [
1010
+ DistributedType.MULTI_XPU,
1011
+ ]:
1012
+ self.distributed_type = DistributedType.MEGATRON_LM
1013
+ megatron_lm_plugin.set_mixed_precision(self._mixed_precision)
1014
+ self.megatron_lm_plugin = megatron_lm_plugin
1015
+ elif self.distributed_type in [DistributedType.MULTI_CPU, DistributedType.MULTI_XPU, DistributedType.NO]:
1016
+ if is_ipex_available():
1017
+ # check if user disables it explicitly
1018
+ self.use_ipex = parse_flag_from_env("ACCELERATE_USE_IPEX", default=True)
1019
+ else:
1020
+ self.use_ipex = False
1021
+ if (
1022
+ self.dynamo_plugin.backend != DynamoBackend.NO
1023
+ and self._mixed_precision == "no"
1024
+ and self.device.type == "cuda"
1025
+ ):
1026
+ torch.backends.cuda.matmul.allow_tf32 = True
1027
+ if (
1028
+ self.dynamo_plugin.backend != DynamoBackend.NO
1029
+ and self._mixed_precision == "no"
1030
+ and self.device.type == "musa"
1031
+ ):
1032
+ torch.backends.musa.matmul.allow_tf32 = True
1033
+ PartialState._shared_state["distributed_type"] = self.distributed_type
1034
+
1035
+ @property
1036
+ def initialized(self) -> bool:
1037
+ return self._shared_state != PartialState._shared_state
1038
+
1039
+ def __repr__(self):
1040
+ repr = PartialState().__repr__() + f"\nMixed precision type: {self.mixed_precision}\n"
1041
+ if self.distributed_type == DistributedType.DEEPSPEED:
1042
+ repr += f"ds_config: {self.deepspeed_plugin.deepspeed_config}\n"
1043
+ return repr
1044
+
1045
+ def _check_initialized(self, mixed_precision=None, cpu=None):
1046
+ "Checks if a modification is trying to be made and the `AcceleratorState` has already been initialized"
1047
+ if self.initialized:
1048
+ err = "AcceleratorState has already been initialized and cannot be changed, restart your runtime completely and pass `{flag}` to `Accelerator()`."
1049
+ if cpu and self.device.type != "cpu":
1050
+ raise ValueError(err.format(flag="cpu=True"))
1051
+ if (
1052
+ mixed_precision is not None
1053
+ and mixed_precision != self._mixed_precision
1054
+ and self.distributed_type != DistributedType.DEEPSPEED
1055
+ ):
1056
+ raise ValueError(err.format(flag=f"mixed_precision='{mixed_precision}'"))
1057
+
1058
+ @property
1059
+ def mixed_precision(self):
1060
+ if self.distributed_type == DistributedType.DEEPSPEED:
1061
+ config = self.deepspeed_plugin.deepspeed_config
1062
+ if config.get("fp16", {}).get("enabled", False):
1063
+ mixed_precision = "fp16"
1064
+ elif config.get("bf16", {}).get("enabled", False):
1065
+ mixed_precision = "bf16"
1066
+ else:
1067
+ mixed_precision = "no"
1068
+ else:
1069
+ mixed_precision = self._mixed_precision
1070
+ return mixed_precision
1071
+
1072
+ @staticmethod
1073
+ def _reset_state(reset_partial_state: bool = False):
1074
+ "Resets `_shared_state`, is used internally and should not be called"
1075
+ AcceleratorState._shared_state.clear()
1076
+ if reset_partial_state:
1077
+ PartialState._reset_state()
1078
+
1079
+ def destroy_process_group(self, group=None):
1080
+ """
1081
+ Destroys the process group. If one is not specified, the default process group is destroyed.
1082
+
1083
+ If `self.fork_lauched` is `True` and `group` is `None`, nothing happens.
1084
+ """
1085
+ PartialState().destroy_process_group(group)
1086
+
1087
+ @property
1088
+ def fork_launched(self):
1089
+ return PartialState().fork_launched
1090
+
1091
+ @property
1092
+ def use_distributed(self):
1093
+ """
1094
+ Whether the Accelerator is configured for distributed training
1095
+ """
1096
+ return PartialState().use_distributed
1097
+
1098
+ @property
1099
+ def is_fsdp2(self) -> bool:
1100
+ return self.distributed_type == DistributedType.FSDP and self.fsdp_plugin.fsdp_version == 2
1101
+
1102
+ @property
1103
+ def is_last_process(self) -> bool:
1104
+ "Returns whether the current process is the last one"
1105
+ return PartialState().is_last_process
1106
+
1107
+ @property
1108
+ def is_main_process(self) -> bool:
1109
+ "Returns whether the current process is the main process"
1110
+ return PartialState().is_main_process
1111
+
1112
+ @property
1113
+ def is_local_main_process(self) -> bool:
1114
+ "Returns whether the current process is the main process on the local node"
1115
+ return PartialState().is_local_main_process
1116
+
1117
+ def wait_for_everyone(self):
1118
+ PartialState().wait_for_everyone()
1119
+
1120
+ @contextmanager
1121
+ def split_between_processes(self, inputs: list | tuple | dict | torch.Tensor, apply_padding: bool = False):
1122
+ """
1123
+ Splits `input` between `self.num_processes` quickly and can be then used on that process. Useful when doing
1124
+ distributed inference, such as with different prompts.
1125
+
1126
+ Note that when using a `dict`, all keys need to have the same number of elements.
1127
+
1128
+ Args:
1129
+ inputs (`list`, `tuple`, `torch.Tensor`, or `dict` of `list`/`tuple`/`torch.Tensor`):
1130
+ The input to split between processes.
1131
+ apply_padding (`bool`, `optional`, defaults to `False`):
1132
+ Whether to apply padding by repeating the last element of the input so that all processes have the same
1133
+ number of elements. Useful when trying to perform actions such as `gather()` on the outputs or passing
1134
+ in less inputs than there are processes. If so, just remember to drop the padded elements afterwards.
1135
+
1136
+
1137
+ Example:
1138
+
1139
+ ```python
1140
+ # Assume there are two processes
1141
+ from accelerate.state import AcceleratorState
1142
+
1143
+ state = AcceleratorState()
1144
+ with state.split_between_processes(["A", "B", "C"]) as inputs:
1145
+ print(inputs)
1146
+ # Process 0
1147
+ ["A", "B"]
1148
+ # Process 1
1149
+ ["C"]
1150
+
1151
+ with state.split_between_processes(["A", "B", "C"], apply_padding=True) as inputs:
1152
+ print(inputs)
1153
+ # Process 0
1154
+ ["A", "B"]
1155
+ # Process 1
1156
+ ["C", "C"]
1157
+ ```
1158
+ """
1159
+ with PartialState().split_between_processes(inputs, apply_padding=apply_padding) as inputs:
1160
+ yield inputs
1161
+
1162
+ @contextmanager
1163
+ def main_process_first(self):
1164
+ """
1165
+ Lets the main process go first inside a with block.
1166
+
1167
+ The other processes will enter the with block after the main process exits.
1168
+ """
1169
+ with PartialState().main_process_first():
1170
+ yield
1171
+
1172
+ @contextmanager
1173
+ def local_main_process_first(self):
1174
+ """
1175
+ Lets the local main process go inside a with block.
1176
+
1177
+ The other processes will enter the with block after the main process exits.
1178
+ """
1179
+ with PartialState().local_main_process_first():
1180
+ yield
1181
+
1182
+ @property
1183
+ def deepspeed_plugin(self):
1184
+ """
1185
+ Returns the currently active DeepSpeedPlugin.
1186
+
1187
+ If not using deepspeed, returns `None`.
1188
+ """
1189
+ # To maintain original behavior, return None if not using deepspeed.
1190
+ if self.distributed_type != DistributedType.DEEPSPEED:
1191
+ return None
1192
+ from accelerate.utils.deepspeed import get_active_deepspeed_plugin
1193
+
1194
+ return get_active_deepspeed_plugin(self)
1195
+
1196
+ @deepspeed_required
1197
+ def get_deepspeed_plugin(self, name: str):
1198
+ """
1199
+ Returns the DeepSpeedPlugin with the given plugin_key.
1200
+ """
1201
+ return self.deepspeed_plugins[name]
1202
+
1203
+ @deepspeed_required
1204
+ def select_deepspeed_plugin(self, name: str = None):
1205
+ """
1206
+ Activates the DeepSpeedPlugin with the given `name`, and will disable all other plugins.
1207
+ """
1208
+ for key, plugin in self.deepspeed_plugins.items():
1209
+ if key != name:
1210
+ plugin._unselect()
1211
+ self.deepspeed_plugins[name].select(_from_accelerator_state=True)
1212
+
1213
+ def print(self, *args, **kwargs):
1214
+ PartialState().print(*args, **kwargs)
1215
+
1216
+ def __getattr__(self, name: str):
1217
+ # By this point we know that no attributes of `self` contain `name`,
1218
+ # so we just modify the error message
1219
+ if name in self._known_attrs:
1220
+ raise AttributeError(
1221
+ f"`AcceleratorState` object has no attribute `{name}`. "
1222
+ "This happens if `AcceleratorState._reset_state()` was called and "
1223
+ "an `Accelerator` or `PartialState` was not reinitialized."
1224
+ )
1225
+ # Raise a typical AttributeError
1226
+ raise AttributeError(f"'AcceleratorState' object has no attribute '{name}'")
1227
+
1228
+
1229
+ class GradientState:
1230
+ """
1231
+ Singleton class that has information related to gradient synchronization for gradient accumulation
1232
+
1233
+ **Available attributes:**
1234
+
1235
+ - **end_of_dataloader** (`bool`) -- Whether we have reached the end the current dataloader
1236
+ - **remainder** (`int`) -- The number of extra samples that were added from padding the dataloader
1237
+ - **sync_gradients** (`bool`) -- Whether the gradients should be synced across all devices
1238
+ - **active_dataloader** (`Optional[DataLoader]`) -- The dataloader that is currently being iterated over
1239
+ - **dataloader_references** (`List[Optional[DataLoader]]`) -- A list of references to the dataloaders that are
1240
+ being iterated over
1241
+ - **num_steps** (`int`) -- The number of steps to accumulate over
1242
+ - **adjust_scheduler** (`bool`) -- Whether the scheduler should be adjusted to account for the gradient
1243
+ accumulation
1244
+ - **sync_with_dataloader** (`bool`) -- Whether the gradients should be synced at the end of the dataloader
1245
+ iteration and the number of total steps reset
1246
+ - **is_xla_gradients_synced** (`bool`) -- Whether the XLA gradients have been synchronized. It is initialized
1247
+ as false. Once gradients have been reduced before the optimizer step, this flag is set to true. Subsequently,
1248
+ after each step, the flag is reset to false. FSDP will always synchronize the gradients, hence
1249
+ is_xla_gradients_synced is always true.
1250
+ """
1251
+
1252
+ _shared_state = SharedDict()
1253
+
1254
+ def __init__(self, gradient_accumulation_plugin: GradientAccumulationPlugin | None = None):
1255
+ self.__dict__ = self._shared_state
1256
+ if not self.initialized:
1257
+ self.sync_gradients = True
1258
+ self._dataloader_references_ref = [None]
1259
+ self.plugin_kwargs = (
1260
+ gradient_accumulation_plugin.to_kwargs() if gradient_accumulation_plugin is not None else {}
1261
+ )
1262
+ self._is_xla_gradients_synced = False
1263
+
1264
+ # Plugin args are different and can be updated
1265
+ if gradient_accumulation_plugin is not None and self.plugin_kwargs != gradient_accumulation_plugin.to_kwargs():
1266
+ self.plugin_kwargs = gradient_accumulation_plugin.to_kwargs()
1267
+
1268
+ @property
1269
+ def num_steps(self) -> int:
1270
+ "Returns the number of steps to accumulate over"
1271
+ return self.plugin_kwargs.get("num_steps", 1)
1272
+
1273
+ @property
1274
+ def adjust_scheduler(self) -> bool:
1275
+ "Returns whether the scheduler should be adjusted"
1276
+ return self.plugin_kwargs.get("adjust_scheduler", False)
1277
+
1278
+ @property
1279
+ def sync_with_dataloader(self) -> bool:
1280
+ "Returns whether the gradients should be synced at the end of the dataloader iteration and the number of total steps reset"
1281
+ return self.plugin_kwargs.get("sync_with_dataloader", True)
1282
+
1283
+ @property
1284
+ def initialized(self) -> bool:
1285
+ "Returns whether the `GradientState` has been initialized"
1286
+ return GradientState._shared_state != {}
1287
+
1288
+ @property
1289
+ def end_of_dataloader(self) -> bool:
1290
+ "Returns whether we have reached the end of the current dataloader"
1291
+ if not self.in_dataloader:
1292
+ return False
1293
+ return self.active_dataloader.end_of_dataloader
1294
+
1295
+ @property
1296
+ def remainder(self) -> int:
1297
+ "Returns the number of extra samples that were added from padding the dataloader"
1298
+ if not self.in_dataloader:
1299
+ return -1
1300
+ return self.active_dataloader.remainder
1301
+
1302
+ def __repr__(self):
1303
+ return (
1304
+ f"Sync Gradients: {self.sync_gradients}\n"
1305
+ f"At end of current dataloader: {self.end_of_dataloader}\n"
1306
+ f"Extra samples added: {self.remainder}\n"
1307
+ f"Gradient accumulation plugin: {self.plugin_kwargs}\n"
1308
+ )
1309
+
1310
+ @property
1311
+ def is_xla_gradients_synced(self):
1312
+ "Returns the value of is_xla_gradients_synced. FSDP will always synchronize the gradients, hence is_xla_gradients_synced is always true."
1313
+ if parse_flag_from_env("ACCELERATE_USE_FSDP", default=False):
1314
+ return True
1315
+ return self._is_xla_gradients_synced
1316
+
1317
+ @is_xla_gradients_synced.setter
1318
+ def is_xla_gradients_synced(self, is_synced):
1319
+ "Set the _is_xla_gradients_synced attribute."
1320
+ self._is_xla_gradients_synced = is_synced
1321
+
1322
+ def _set_sync_gradients(self, sync_gradients):
1323
+ "Private function that sets whether gradients should be synchronized. Users should not have to call this."
1324
+ self.sync_gradients = sync_gradients
1325
+ # Allow grad-sync to automatically work on TPUs
1326
+ if (
1327
+ self.sync_gradients
1328
+ and is_torch_xla_available(check_is_tpu=True)
1329
+ and PartialState().distributed_type == DistributedType.XLA
1330
+ ):
1331
+ xm.mark_step()
1332
+
1333
+ def _add_dataloader(self, dataloader):
1334
+ "Private function that adds a dataloader to `self.dataloader_references` and sets `in_dataloader` to `True`. Users should not have to call this."
1335
+ # We explicitly use assignment to ensure that the property setter is triggered, which is required for garbage collection.
1336
+ # Avoid using self.dataloader_references.append as it will not trigger the setter.
1337
+ self.dataloader_references += [dataloader]
1338
+
1339
+ def _remove_dataloader(self, dataloader):
1340
+ "Private function that removes a dataloader from `self.dataloader_references` and sets `in_dataloader` to `False` if there are no more dataloaders. Users should not have to call this."
1341
+ # We explicitly use assignment to ensure that the property setter is triggered.
1342
+ self.dataloader_references = [
1343
+ dataloader_ref for dataloader_ref in self.dataloader_references if dataloader_ref != dataloader
1344
+ ]
1345
+
1346
+ @property
1347
+ def active_dataloader(self):
1348
+ return self.dataloader_references[-1]
1349
+
1350
+ @property
1351
+ def dataloader_references(self):
1352
+ # We use a property getter and setter with weakrefs to avoid circular references that prevent garbage collection
1353
+ return [reference() if reference is not None else reference for reference in self._dataloader_references_ref]
1354
+
1355
+ @dataloader_references.setter
1356
+ def dataloader_references(self, references):
1357
+ self._dataloader_references_ref = [
1358
+ weakref.ref(dataloader) if dataloader is not None else dataloader for dataloader in references
1359
+ ]
1360
+
1361
+ @property
1362
+ def in_dataloader(self) -> bool:
1363
+ "Returns whether the current process is in a dataloader"
1364
+ return self.active_dataloader is not None
1365
+
1366
+ @staticmethod
1367
+ def _reset_state():
1368
+ "Resets `_shared_state`, is used internally and should not be called"
1369
+ GradientState._shared_state.clear()
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/__init__.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from .testing import (
15
+ DEFAULT_LAUNCH_COMMAND,
16
+ are_the_same_tensors,
17
+ assert_exception,
18
+ capture_call_output,
19
+ device_count,
20
+ execute_subprocess_async,
21
+ get_launch_command,
22
+ get_torch_dist_unique_port,
23
+ memory_allocated_func,
24
+ path_in_accelerate_package,
25
+ pytest_xdist_worker_id,
26
+ require_bnb,
27
+ require_cpu,
28
+ require_cuda,
29
+ require_cuda_or_hpu,
30
+ require_cuda_or_xpu,
31
+ require_fp8,
32
+ require_fp16,
33
+ require_huggingface_suite,
34
+ require_mlu,
35
+ require_mps,
36
+ require_multi_device,
37
+ require_multi_gpu,
38
+ require_multi_gpu_or_xpu,
39
+ require_multi_xpu,
40
+ require_musa,
41
+ require_non_cpu,
42
+ require_non_hpu,
43
+ require_non_torch_xla,
44
+ require_non_xpu,
45
+ require_npu,
46
+ require_pippy,
47
+ require_sdaa,
48
+ require_single_device,
49
+ require_single_gpu,
50
+ require_single_xpu,
51
+ require_torch_min_version,
52
+ require_torchao,
53
+ require_torchvision,
54
+ require_tpu,
55
+ require_transformer_engine,
56
+ require_xpu,
57
+ run_first,
58
+ skip,
59
+ slow,
60
+ torch_device,
61
+ )
62
+ from .training import RegressionDataset, RegressionModel, RegressionModel4XPU
63
+
64
+
65
+ from .scripts import test_script, test_sync, test_ops # isort: skip
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/examples.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """
17
+ A collection of utilities for comparing `examples/complete_*_example.py` scripts with the capabilities inside of each
18
+ `examples/by_feature` example. `compare_against_test` is the main function that should be used when testing, while the
19
+ others are used to either get the code that matters, or to preprocess them (such as stripping comments)
20
+ """
21
+
22
+ import os
23
+
24
+
25
+ def get_function_contents_by_name(lines: list[str], name: str):
26
+ """
27
+ Extracts a function from `lines` of segmented source code with the name `name`.
28
+
29
+ Args:
30
+ lines (`List[str]`):
31
+ Source code of a script separated by line.
32
+ name (`str`):
33
+ The name of the function to extract. Should be either `training_function` or `main`
34
+ """
35
+ if name != "training_function" and name != "main":
36
+ raise ValueError(f"Incorrect function name passed: {name}, choose either 'main' or 'training_function'")
37
+ good_lines, found_start = [], False
38
+ for line in lines:
39
+ if not found_start and f"def {name}" in line:
40
+ found_start = True
41
+ good_lines.append(line)
42
+ continue
43
+ if found_start:
44
+ if name == "training_function" and "def main" in line:
45
+ return good_lines
46
+ if name == "main" and "if __name__" in line:
47
+ return good_lines
48
+ good_lines.append(line)
49
+
50
+
51
+ def clean_lines(lines: list[str]):
52
+ """
53
+ Filters `lines` and removes any entries that start with a comment ('#') or is just a newline ('\n')
54
+
55
+ Args:
56
+ lines (`List[str]`):
57
+ Source code of a script separated by line.
58
+ """
59
+ return [line for line in lines if not line.lstrip().startswith("#") and line != "\n"]
60
+
61
+
62
+ def compare_against_test(base_filename: str, feature_filename: str, parser_only: bool, secondary_filename: str = None):
63
+ """
64
+ Tests whether the additional code inside of `feature_filename` was implemented in `base_filename`. This should be
65
+ used when testing to see if `complete_*_.py` examples have all of the implementations from each of the
66
+ `examples/by_feature/*` scripts.
67
+
68
+ It utilizes `nlp_example.py` to extract out all of the repeated training code, so that only the new additional code
69
+ is examined and checked. If something *other* than `nlp_example.py` should be used, such as `cv_example.py` for the
70
+ `complete_cv_example.py` script, it should be passed in for the `secondary_filename` parameter.
71
+
72
+ Args:
73
+ base_filename (`str` or `os.PathLike`):
74
+ The filepath of a single "complete" example script to test, such as `examples/complete_cv_example.py`
75
+ feature_filename (`str` or `os.PathLike`):
76
+ The filepath of a single feature example script. The contents of this script are checked to see if they
77
+ exist in `base_filename`
78
+ parser_only (`bool`):
79
+ Whether to compare only the `main()` sections in both files, or to compare the contents of
80
+ `training_loop()`
81
+ secondary_filename (`str`, *optional*):
82
+ A potential secondary filepath that should be included in the check. This function extracts the base
83
+ functionalities off of "examples/nlp_example.py", so if `base_filename` is a script other than
84
+ `complete_nlp_example.py`, the template script should be included here. Such as `examples/cv_example.py`
85
+ """
86
+ with open(base_filename) as f:
87
+ base_file_contents = f.readlines()
88
+ with open(os.path.abspath(os.path.join("examples", "nlp_example.py"))) as f:
89
+ full_file_contents = f.readlines()
90
+ with open(feature_filename) as f:
91
+ feature_file_contents = f.readlines()
92
+ if secondary_filename is not None:
93
+ with open(secondary_filename) as f:
94
+ secondary_file_contents = f.readlines()
95
+
96
+ # This is our base, we remove all the code from here in our `full_filename` and `feature_filename` to find the new content
97
+ if parser_only:
98
+ base_file_func = clean_lines(get_function_contents_by_name(base_file_contents, "main"))
99
+ full_file_func = clean_lines(get_function_contents_by_name(full_file_contents, "main"))
100
+ feature_file_func = clean_lines(get_function_contents_by_name(feature_file_contents, "main"))
101
+ if secondary_filename is not None:
102
+ secondary_file_func = clean_lines(get_function_contents_by_name(secondary_file_contents, "main"))
103
+ else:
104
+ base_file_func = clean_lines(get_function_contents_by_name(base_file_contents, "training_function"))
105
+ full_file_func = clean_lines(get_function_contents_by_name(full_file_contents, "training_function"))
106
+ feature_file_func = clean_lines(get_function_contents_by_name(feature_file_contents, "training_function"))
107
+ if secondary_filename is not None:
108
+ secondary_file_func = clean_lines(
109
+ get_function_contents_by_name(secondary_file_contents, "training_function")
110
+ )
111
+
112
+ _dl_line = "train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)\n"
113
+
114
+ # Specific code in our script that differs from the full version, aka what is new
115
+ new_feature_code = []
116
+ passed_idxs = [] # We keep track of the idxs just in case it's a repeated statement
117
+ it = iter(feature_file_func)
118
+ for i in range(len(feature_file_func) - 1):
119
+ if i not in passed_idxs:
120
+ line = next(it)
121
+ if (line not in full_file_func) and (line.lstrip() != _dl_line):
122
+ if "TESTING_MOCKED_DATALOADERS" not in line:
123
+ new_feature_code.append(line)
124
+ passed_idxs.append(i)
125
+ else:
126
+ # Skip over the `config['num_epochs'] = 2` statement
127
+ _ = next(it)
128
+
129
+ # Extract out just the new parts from the full_file_training_func
130
+ new_full_example_parts = []
131
+ passed_idxs = [] # We keep track of the idxs just in case it's a repeated statement
132
+ for i, line in enumerate(base_file_func):
133
+ if i not in passed_idxs:
134
+ if (line not in full_file_func) and (line.lstrip() != _dl_line):
135
+ if "TESTING_MOCKED_DATALOADERS" not in line:
136
+ new_full_example_parts.append(line)
137
+ passed_idxs.append(i)
138
+
139
+ # Finally, get the overall diff
140
+ diff_from_example = [line for line in new_feature_code if line not in new_full_example_parts]
141
+ if secondary_filename is not None:
142
+ diff_from_two = [line for line in full_file_contents if line not in secondary_file_func]
143
+ diff_from_example = [line for line in diff_from_example if line not in diff_from_two]
144
+
145
+ return diff_from_example
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/test_checkpointing.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import argparse
15
+ import json
16
+ import os
17
+
18
+ import evaluate
19
+ import torch
20
+ from datasets import load_dataset
21
+ from torch.optim import AdamW
22
+ from torch.utils.data import DataLoader
23
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
24
+
25
+ from accelerate import Accelerator, DistributedType
26
+ from accelerate.utils.deepspeed import DummyOptim, DummyScheduler
27
+
28
+
29
+ MAX_GPU_BATCH_SIZE = 16
30
+ EVAL_BATCH_SIZE = 32
31
+
32
+
33
+ def get_dataloaders(accelerator: Accelerator, batch_size: int = 16, model_name: str = "bert-base-cased"):
34
+ """
35
+ Creates a set of `DataLoader`s for the `glue` dataset.
36
+
37
+ Args:
38
+ accelerator (`Accelerator`):
39
+ An `Accelerator` object
40
+ batch_size (`int`, *optional*):
41
+ The batch size for the train and validation DataLoaders.
42
+ model_name (`str`, *optional*):
43
+ """
44
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
45
+ datasets = load_dataset("glue", "mrpc")
46
+
47
+ def tokenize_function(examples):
48
+ # max_length=None => use the model max length (it's actually the default)
49
+ outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
50
+ return outputs
51
+
52
+ # Apply the method we just defined to all the examples in all the splits of the dataset
53
+ tokenized_datasets = datasets.map(
54
+ tokenize_function, batched=True, remove_columns=["idx", "sentence1", "sentence2"], load_from_cache_file=False
55
+ )
56
+
57
+ # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
58
+ # transformers library
59
+ tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
60
+
61
+ def collate_fn(examples):
62
+ # On TPU it's best to pad everything to the same length or training will be very slow.
63
+ if accelerator.distributed_type == DistributedType.XLA:
64
+ return tokenizer.pad(examples, padding="max_length", max_length=128, return_tensors="pt")
65
+ return tokenizer.pad(examples, padding="longest", return_tensors="pt")
66
+
67
+ # Instantiate dataloaders.
68
+ train_dataloader = DataLoader(
69
+ tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
70
+ )
71
+ eval_dataloader = DataLoader(
72
+ tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
73
+ )
74
+
75
+ return train_dataloader, eval_dataloader
76
+
77
+
78
+ def evaluation_loop(accelerator, model, eval_dataloader, metric):
79
+ model.eval()
80
+ samples_seen = 0
81
+ for step, batch in enumerate(eval_dataloader):
82
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
83
+ batch.to(accelerator.device)
84
+ with torch.no_grad():
85
+ outputs = model(**batch)
86
+ predictions = outputs.logits.argmax(dim=-1)
87
+ # It is slightly faster to call this once, than multiple times
88
+ predictions, references = accelerator.gather(
89
+ (predictions, batch["labels"])
90
+ ) # If we are in a multiprocess environment, the last batch has duplicates
91
+ if accelerator.use_distributed:
92
+ if step == len(eval_dataloader) - 1:
93
+ predictions = predictions[: len(eval_dataloader.dataset) - samples_seen]
94
+ references = references[: len(eval_dataloader.dataset) - samples_seen]
95
+ else:
96
+ samples_seen += references.shape[0]
97
+ metric.add_batch(
98
+ predictions=predictions,
99
+ references=references,
100
+ )
101
+
102
+ eval_metric = metric.compute()
103
+ return eval_metric["accuracy"]
104
+
105
+
106
+ def training_function(config, args):
107
+ # Initialize accelerator
108
+ accelerator = Accelerator()
109
+
110
+ # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
111
+ lr = config["lr"]
112
+ num_epochs = int(config["num_epochs"])
113
+ seed = int(config["seed"])
114
+ batch_size = int(config["batch_size"])
115
+ model_name = args.model_name_or_path
116
+
117
+ set_seed(seed)
118
+ train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size, model_name)
119
+
120
+ # Instantiate the model (we build the model here so that the seed also control new weights initialization)
121
+ model = AutoModelForSequenceClassification.from_pretrained(model_name, return_dict=True)
122
+
123
+ # Instantiate optimizer
124
+ optimizer_cls = (
125
+ AdamW
126
+ if accelerator.state.deepspeed_plugin is None
127
+ or "optimizer" not in accelerator.state.deepspeed_plugin.deepspeed_config
128
+ else DummyOptim
129
+ )
130
+ optimizer = optimizer_cls(params=model.parameters(), lr=lr)
131
+
132
+ if accelerator.state.deepspeed_plugin is not None:
133
+ gradient_accumulation_steps = accelerator.state.deepspeed_plugin.deepspeed_config[
134
+ "gradient_accumulation_steps"
135
+ ]
136
+ else:
137
+ gradient_accumulation_steps = 1
138
+ max_training_steps = (len(train_dataloader) * num_epochs) // gradient_accumulation_steps
139
+
140
+ # Instantiate scheduler
141
+ if (
142
+ accelerator.state.deepspeed_plugin is None
143
+ or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config
144
+ ):
145
+ lr_scheduler = get_linear_schedule_with_warmup(
146
+ optimizer=optimizer,
147
+ num_warmup_steps=0,
148
+ num_training_steps=max_training_steps,
149
+ )
150
+ else:
151
+ lr_scheduler = DummyScheduler(optimizer, total_num_steps=max_training_steps, warmup_num_steps=0)
152
+
153
+ # Prepare everything
154
+ # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
155
+ # prepare method.
156
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
157
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
158
+ )
159
+
160
+ # We need to keep track of how many total steps we have iterated over
161
+ overall_step = 0
162
+ # We also need to keep track of the stating epoch so files are named properly
163
+ starting_epoch = 0
164
+ metric = evaluate.load("glue", "mrpc")
165
+ ending_epoch = num_epochs
166
+
167
+ if args.partial_train_epoch is not None:
168
+ ending_epoch = args.partial_train_epoch
169
+
170
+ if args.resume_from_checkpoint:
171
+ accelerator.load_state(args.resume_from_checkpoint)
172
+ epoch_string = args.resume_from_checkpoint.split("epoch_")[1]
173
+ state_epoch_num = ""
174
+ for char in epoch_string:
175
+ if char.isdigit():
176
+ state_epoch_num += char
177
+ else:
178
+ break
179
+ starting_epoch = int(state_epoch_num) + 1
180
+ accuracy = evaluation_loop(accelerator, model, eval_dataloader, metric)
181
+ accelerator.print("resumed checkpoint performance:", accuracy)
182
+ accelerator.print("resumed checkpoint's scheduler's lr:", lr_scheduler.get_lr()[0])
183
+ accelerator.print("resumed optimizers's lr:", optimizer.param_groups[0]["lr"])
184
+ with open(os.path.join(args.output_dir, f"state_{starting_epoch - 1}.json")) as f:
185
+ resumed_state = json.load(f)
186
+ assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed"
187
+ assert resumed_state["lr"] == lr_scheduler.get_lr()[0], (
188
+ "Scheduler learning rate mismatch, loading from checkpoint failed"
189
+ )
190
+ assert resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"], (
191
+ "Optimizer learning rate mismatch, loading from checkpoint failed"
192
+ )
193
+ assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed"
194
+ return
195
+
196
+ # Now we train the model
197
+ state = {}
198
+ for epoch in range(starting_epoch, ending_epoch):
199
+ model.train()
200
+ for step, batch in enumerate(train_dataloader):
201
+ outputs = model(**batch)
202
+ loss = outputs.loss
203
+ loss = loss / gradient_accumulation_steps
204
+ accelerator.backward(loss)
205
+ if step % gradient_accumulation_steps == 0:
206
+ optimizer.step()
207
+ lr_scheduler.step()
208
+ optimizer.zero_grad()
209
+
210
+ overall_step += 1
211
+ output_dir = f"epoch_{epoch}"
212
+ output_dir = os.path.join(args.output_dir, output_dir)
213
+ accelerator.save_state(output_dir)
214
+ accuracy = evaluation_loop(accelerator, model, eval_dataloader, metric)
215
+ state["accuracy"] = accuracy
216
+ state["lr"] = lr_scheduler.get_lr()[0]
217
+ state["optimizer_lr"] = optimizer.param_groups[0]["lr"]
218
+ state["epoch"] = epoch
219
+ state["step"] = overall_step
220
+ accelerator.print(f"epoch {epoch}:", state)
221
+
222
+ accelerator.wait_for_everyone()
223
+ if accelerator.is_main_process:
224
+ with open(os.path.join(args.output_dir, f"state_{epoch}.json"), "w") as f:
225
+ json.dump(state, f)
226
+ accelerator.end_training()
227
+
228
+
229
+ def main():
230
+ parser = argparse.ArgumentParser(description="Simple example of training script tracking peak GPU memory usage.")
231
+ parser.add_argument(
232
+ "--model_name_or_path",
233
+ type=str,
234
+ default="bert-base-cased",
235
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
236
+ required=False,
237
+ )
238
+ parser.add_argument(
239
+ "--output_dir",
240
+ type=str,
241
+ default=".",
242
+ help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory.",
243
+ )
244
+ parser.add_argument(
245
+ "--resume_from_checkpoint",
246
+ type=str,
247
+ default=None,
248
+ help="If the training should continue from a checkpoint folder.",
249
+ )
250
+ parser.add_argument(
251
+ "--partial_train_epoch",
252
+ type=int,
253
+ default=None,
254
+ help="If passed, the training will stop after this number of epochs.",
255
+ )
256
+ parser.add_argument(
257
+ "--num_epochs",
258
+ type=int,
259
+ default=2,
260
+ help="Number of train epochs.",
261
+ )
262
+ args = parser.parse_args()
263
+ config = {"lr": 2e-5, "num_epochs": args.num_epochs, "seed": 42, "batch_size": 16}
264
+
265
+ training_function(config, args)
266
+
267
+
268
+ if __name__ == "__main__":
269
+ main()
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/test_ds_multiple_model.py ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ Test script for verifying multiple models can be utilized with Accelerate + DeepSpeed:
17
+
18
+ Scenario 1: One model is training, another model is being used for inference/logits to impact training in some form.
19
+ Scenario 2: Two models are training simultaneously, which means two optimizers, etc.
20
+ """
21
+
22
+ import argparse
23
+ from pathlib import Path
24
+
25
+ import evaluate
26
+ import torch
27
+ from datasets import load_dataset
28
+ from torch.optim import AdamW
29
+ from torch.utils.data import DataLoader
30
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup
31
+
32
+ from accelerate import Accelerator, DeepSpeedPlugin, DistributedType
33
+ from accelerate.state import AcceleratorState
34
+ from accelerate.utils.deepspeed import get_active_deepspeed_plugin
35
+
36
+
37
+ MAX_GPU_BATCH_SIZE = 16
38
+ EVAL_BATCH_SIZE = 32
39
+
40
+
41
+ class NoiseModel(torch.nn.Module):
42
+ def __init__(self, noise_factor=0.1):
43
+ super().__init__()
44
+ self.noise_factor = torch.nn.Parameter(torch.tensor(noise_factor, dtype=torch.float32))
45
+
46
+ def forward(self, loss):
47
+ return loss * self.noise_factor
48
+
49
+
50
+ def get_dataloaders(accelerator: Accelerator, batch_size: int = 16, model_name: str = "bert-base-cased"):
51
+ """
52
+ Creates a set of `DataLoader`s for the `glue` dataset.
53
+
54
+ Args:
55
+ accelerator (`Accelerator`):
56
+ An `Accelerator` object
57
+ batch_size (`int`, *optional*):
58
+ The batch size for the train and validation DataLoaders.
59
+ model_name (`str`, *optional*):
60
+ """
61
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
62
+ datasets = load_dataset("glue", "mrpc")
63
+
64
+ def tokenize_function(examples):
65
+ # max_length=None => use the model max length (it's actually the default)
66
+ outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
67
+ return outputs
68
+
69
+ # Apply the method we just defined to all the examples in all the splits of the dataset
70
+ tokenized_datasets = datasets.map(
71
+ tokenize_function, batched=True, remove_columns=["idx", "sentence1", "sentence2"], load_from_cache_file=False
72
+ )
73
+
74
+ # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
75
+ # transformers library
76
+ tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
77
+
78
+ def collate_fn(examples):
79
+ # On TPU it's best to pad everything to the same length or training will be very slow.
80
+ if accelerator.distributed_type == DistributedType.XLA:
81
+ return tokenizer.pad(examples, padding="max_length", max_length=128, return_tensors="pt")
82
+ return tokenizer.pad(examples, padding="longest", return_tensors="pt")
83
+
84
+ # Instantiate dataloaders.
85
+ train_dataloader = DataLoader(
86
+ tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
87
+ )
88
+ eval_dataloader = DataLoader(
89
+ tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
90
+ )
91
+
92
+ return train_dataloader, eval_dataloader
93
+
94
+
95
+ test_file_path = __file__
96
+ path = Path(test_file_path).resolve()
97
+ test_file_dir_str = str(path.parent.parent.parent.parent.parent.parent)
98
+
99
+ # Create our DS plugins
100
+ # We use custom schedulers and optimizers, hence `model_only`
101
+ ds_config_file = dict(
102
+ zero2=f"{test_file_dir_str}/tests/deepspeed/ds_config_zero2_model_only.json",
103
+ zero3=f"{test_file_dir_str}/tests/deepspeed/ds_config_zero3_model_only.json",
104
+ )
105
+
106
+
107
+ def single_model_training(config, args):
108
+ # Training a single model, we have a `noise` model that is untrainable used to inject some noise into the training process
109
+ num_epochs = config["num_epochs"]
110
+ zero2_plugin = DeepSpeedPlugin(hf_ds_config=ds_config_file["zero2"])
111
+ zero3_plugin = DeepSpeedPlugin(hf_ds_config=ds_config_file["zero3"])
112
+
113
+ deepspeed_plugins = {"training": zero2_plugin, "inference": zero3_plugin}
114
+
115
+ # Initialize accelerator
116
+ accelerator = Accelerator(
117
+ deepspeed_plugins=deepspeed_plugins,
118
+ mixed_precision="bf16",
119
+ )
120
+
121
+ # Initialize model under zero2 plugin
122
+ assert get_active_deepspeed_plugin(accelerator.state) is zero2_plugin
123
+ train_model = AutoModelForSequenceClassification.from_pretrained(args.model_name_or_path)
124
+ train_dataloader, eval_dataloader = get_dataloaders(
125
+ accelerator, batch_size=config["batch_size"], model_name=args.model_name_or_path
126
+ )
127
+ max_training_steps = len(train_dataloader) * config["num_epochs"]
128
+ optimizer = AdamW(train_model.parameters(), lr=config["lr"])
129
+ lr_scheduler = get_linear_schedule_with_warmup(
130
+ optimizer, num_warmup_steps=0, num_training_steps=max_training_steps
131
+ )
132
+
133
+ train_dataloader, eval_dataloader, train_model, optimizer, lr_scheduler = accelerator.prepare(
134
+ train_dataloader, eval_dataloader, train_model, optimizer, lr_scheduler
135
+ )
136
+
137
+ # Now prepare the model under zero3 plugin
138
+ accelerator.state.select_deepspeed_plugin("inference")
139
+ assert get_active_deepspeed_plugin(accelerator.state) is zero3_plugin
140
+ inference_model = NoiseModel()
141
+ inference_model = accelerator.prepare(inference_model)
142
+ inference_model.eval()
143
+
144
+ # Run training loop
145
+ accelerator.state.select_deepspeed_plugin("training")
146
+ # We also need to keep track of the stating epoch so files are named properly
147
+ starting_epoch = 0
148
+
149
+ # Now we train the model
150
+ best_performance = 0
151
+ metric = evaluate.load("glue", "mrpc")
152
+ performance_metric = {}
153
+ for epoch in range(starting_epoch, num_epochs):
154
+ train_model.train()
155
+ inference_model.train()
156
+ for step, batch in enumerate(train_dataloader):
157
+ with accelerator.accumulate(train_model):
158
+ outputs_1 = train_model(**batch)
159
+ with torch.no_grad():
160
+ outputs_2 = inference_model(outputs_1.loss)
161
+ # Combine the losses
162
+ loss = outputs_1.loss + outputs_2
163
+ accelerator.backward(loss)
164
+ optimizer.step()
165
+ lr_scheduler.step()
166
+ optimizer.zero_grad()
167
+
168
+ train_model.eval()
169
+ for step, batch in enumerate(eval_dataloader):
170
+ with torch.no_grad():
171
+ outputs = train_model(**batch)
172
+ predictions = outputs.logits.argmax(dim=-1)
173
+ # It is slightly faster to call this once, than multiple times
174
+ predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
175
+ metric.add_batch(
176
+ predictions=predictions,
177
+ references=references,
178
+ )
179
+
180
+ eval_metric = metric.compute()
181
+ # Use accelerator.print to print only on the main process.
182
+ accelerator.print(f"epoch {epoch}:", eval_metric)
183
+ performance_metric[f"epoch-{epoch}"] = eval_metric["accuracy"]
184
+
185
+ if best_performance < eval_metric["accuracy"]:
186
+ best_performance = eval_metric["accuracy"]
187
+ assert best_performance > performance_metric["epoch-0"]
188
+
189
+
190
+ def multiple_model_training(config, args):
191
+ # This will essentially be like a k-fold model, but one model is Zero-2 and another model is Zero-3
192
+ num_epochs = config["num_epochs"]
193
+ zero2_plugin = DeepSpeedPlugin(hf_ds_config=ds_config_file["zero2"])
194
+ zero3_plugin = DeepSpeedPlugin(hf_ds_config=ds_config_file["zero3"])
195
+
196
+ deepspeed_plugins = {"zero2": zero2_plugin, "zero3": zero3_plugin}
197
+
198
+ # Initialize accelerator
199
+ zero2_accelerator = Accelerator(
200
+ deepspeed_plugins=deepspeed_plugins,
201
+ mixed_precision="bf16",
202
+ )
203
+
204
+ # Since an `AcceleratorState` has already been made, we can just reuse it here
205
+ zero3_accelerator = Accelerator()
206
+
207
+ # Initialize model under zero2 plugin
208
+ assert get_active_deepspeed_plugin(zero2_accelerator.state) is zero2_plugin
209
+ zero2_model = AutoModelForSequenceClassification.from_pretrained(args.model_name_or_path)
210
+ train_dataloader, eval_dataloader = get_dataloaders(
211
+ zero2_accelerator, batch_size=config["batch_size"], model_name=args.model_name_or_path
212
+ )
213
+ max_training_steps = len(train_dataloader) * config["num_epochs"]
214
+ zero2_optimizer = AdamW(zero2_model.parameters(), lr=config["lr"])
215
+ zero2_lr_scheduler = get_linear_schedule_with_warmup(
216
+ zero2_optimizer, num_warmup_steps=0, num_training_steps=max_training_steps
217
+ )
218
+
219
+ train_dataloader, eval_dataloader, zero2_model, zero2_optimizer, zero2_lr_scheduler = zero2_accelerator.prepare(
220
+ train_dataloader, eval_dataloader, zero2_model, zero2_optimizer, zero2_lr_scheduler
221
+ )
222
+ assert zero2_accelerator.deepspeed_engine_wrapped.engine is zero2_model
223
+
224
+ # now do Zero3
225
+ zero3_accelerator.state.select_deepspeed_plugin("zero3")
226
+ zero3_plugin.deepspeed_config["train_micro_batch_size_per_gpu"] = zero2_plugin.deepspeed_config[
227
+ "train_micro_batch_size_per_gpu"
228
+ ]
229
+ assert get_active_deepspeed_plugin(zero3_accelerator.state) is zero3_plugin
230
+ zero3_model = AutoModelForSequenceClassification.from_pretrained(args.model_name_or_path)
231
+ zero3_optimizer = AdamW(zero3_model.parameters(), lr=config["lr"])
232
+ zero3_lr_scheduler = get_linear_schedule_with_warmup(
233
+ zero3_optimizer, num_warmup_steps=0, num_training_steps=max_training_steps
234
+ )
235
+ zero3_model, zero3_optimizer, zero3_lr_scheduler = zero3_accelerator.prepare(
236
+ zero3_model, zero3_optimizer, zero3_lr_scheduler
237
+ )
238
+ assert zero3_accelerator.deepspeed_engine_wrapped.engine is zero3_model
239
+
240
+ # Run training loop
241
+ starting_epoch = 0
242
+
243
+ # Now we train the model
244
+ best_performance_a = 0
245
+ best_performance_b = 0
246
+ metric_a = evaluate.load("glue", "mrpc")
247
+ metric_b = evaluate.load("glue", "mrpc")
248
+ performance_metric_a = {}
249
+ performance_metric_b = {}
250
+ for epoch in range(starting_epoch, num_epochs):
251
+ zero2_model.train()
252
+ zero3_model.train()
253
+ for step, batch in enumerate(train_dataloader):
254
+ with zero2_accelerator.accumulate(zero2_model, zero3_model):
255
+ outputs_1 = zero2_model(**batch)
256
+ zero2_accelerator.backward(outputs_1.loss)
257
+ zero2_optimizer.step()
258
+ zero2_lr_scheduler.step()
259
+ zero2_optimizer.zero_grad()
260
+ outputs_2 = zero3_model(**batch)
261
+ zero3_accelerator.backward(outputs_2.loss)
262
+ zero3_optimizer.step()
263
+ zero3_lr_scheduler.step()
264
+ zero3_optimizer.zero_grad()
265
+
266
+ zero2_model.eval()
267
+ zero3_model.eval()
268
+ for step, batch in enumerate(eval_dataloader):
269
+ with torch.no_grad():
270
+ logits_a = zero2_model(**batch).logits
271
+ logits_b = zero3_model(**batch).logits
272
+ # Combine the logits from both models
273
+ predictions_a = logits_a.argmax(dim=-1)
274
+ predictions_b = logits_b.argmax(dim=-1)
275
+ # It is slightly faster to call this once, than multiple times
276
+ predictions_a, predictions_b, references = zero2_accelerator.gather_for_metrics(
277
+ (predictions_a, predictions_b, batch["labels"])
278
+ )
279
+ metric_a.add_batch(
280
+ predictions=predictions_a,
281
+ references=references,
282
+ )
283
+ metric_b.add_batch(
284
+ predictions=predictions_b,
285
+ references=references,
286
+ )
287
+
288
+ eval_metric_a = metric_a.compute()
289
+ eval_metric_b = metric_b.compute()
290
+ # Use accelerator.print to print only on the main process.
291
+ zero2_accelerator.print(f"epoch {epoch}:", eval_metric_a, eval_metric_b)
292
+ performance_metric_a[f"epoch-{epoch}"] = eval_metric_a["accuracy"]
293
+ performance_metric_b[f"epoch-{epoch}"] = eval_metric_b["accuracy"]
294
+
295
+ if best_performance_a < eval_metric_a["accuracy"]:
296
+ best_performance_a = eval_metric_a["accuracy"]
297
+ if best_performance_b < eval_metric_b["accuracy"]:
298
+ best_performance_b = eval_metric_b["accuracy"]
299
+ assert best_performance_a > performance_metric_a["epoch-0"]
300
+ assert best_performance_b > performance_metric_b["epoch-0"]
301
+
302
+
303
+ def main():
304
+ parser = argparse.ArgumentParser(description="Simple example of training script tracking peak GPU memory usage.")
305
+ parser.add_argument(
306
+ "--model_name_or_path",
307
+ type=str,
308
+ default="bert-base-cased",
309
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
310
+ required=False,
311
+ )
312
+ parser.add_argument(
313
+ "--performance_lower_bound",
314
+ type=float,
315
+ default=None,
316
+ help="Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.",
317
+ )
318
+ parser.add_argument(
319
+ "--num_epochs",
320
+ type=int,
321
+ default=2,
322
+ help="Number of train epochs.",
323
+ )
324
+ args = parser.parse_args()
325
+ config = {"lr": 2e-5, "num_epochs": args.num_epochs, "seed": 42, "batch_size": 16}
326
+ single_model_training(config, args)
327
+ AcceleratorState._reset_state(True)
328
+ multiple_model_training(config, args)
329
+
330
+
331
+ if __name__ == "__main__":
332
+ main()
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/test_metrics.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import logging
16
+ import math
17
+ import os
18
+ from copy import deepcopy
19
+
20
+ import datasets
21
+ import evaluate
22
+ import torch
23
+ import transformers
24
+ from datasets import load_dataset
25
+ from torch.utils.data import DataLoader, IterableDataset
26
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer
27
+
28
+ from accelerate import Accelerator, DataLoaderConfiguration, DistributedType
29
+ from accelerate.data_loader import DataLoaderDispatcher
30
+ from accelerate.test_utils import RegressionDataset, RegressionModel, torch_device
31
+ from accelerate.utils import is_torch_xla_available, set_seed
32
+
33
+
34
+ os.environ["TRANSFORMERS_NO_ADVISORY_WARNINGS"] = "true"
35
+
36
+
37
+ class ListHandler(logging.Handler):
38
+ def __init__(self, *args, **kwargs):
39
+ super().__init__(*args, **kwargs)
40
+ self.logs = []
41
+
42
+ def emit(self, record):
43
+ self.logs.append(record)
44
+
45
+
46
+ def get_basic_setup(accelerator, num_samples=82, batch_size=16):
47
+ "Returns everything needed to perform basic training"
48
+ set_seed(42)
49
+ model = RegressionModel()
50
+ ddp_model = deepcopy(model)
51
+ dset = RegressionDataset(length=num_samples)
52
+ dataloader = DataLoader(dset, batch_size=batch_size)
53
+ model.to(accelerator.device)
54
+ ddp_model, dataloader = accelerator.prepare(ddp_model, dataloader)
55
+ return model, ddp_model, dataloader
56
+
57
+
58
+ def get_dataloader(accelerator: Accelerator, use_longest=False):
59
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/mrpc-bert-base-cased")
60
+ dataset = load_dataset("glue", "mrpc", split="validation")
61
+
62
+ def tokenize_function(examples):
63
+ outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
64
+ return outputs
65
+
66
+ with accelerator.main_process_first():
67
+ tokenized_datasets = dataset.map(
68
+ tokenize_function,
69
+ batched=True,
70
+ remove_columns=["idx", "sentence1", "sentence2"],
71
+ )
72
+
73
+ tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
74
+
75
+ def collate_fn(examples):
76
+ if use_longest:
77
+ return tokenizer.pad(examples, padding="longest", return_tensors="pt")
78
+ return tokenizer.pad(examples, padding="max_length", max_length=128, return_tensors="pt")
79
+
80
+ return DataLoader(tokenized_datasets, shuffle=False, collate_fn=collate_fn, batch_size=16)
81
+
82
+
83
+ def get_mrpc_setup(dispatch_batches, split_batches):
84
+ dataloader_config = DataLoaderConfiguration(dispatch_batches=dispatch_batches, split_batches=split_batches)
85
+ accelerator = Accelerator(dataloader_config=dataloader_config)
86
+ dataloader = get_dataloader(accelerator, not dispatch_batches)
87
+ model = AutoModelForSequenceClassification.from_pretrained(
88
+ "hf-internal-testing/mrpc-bert-base-cased", return_dict=True
89
+ )
90
+ ddp_model, ddp_dataloader = accelerator.prepare(model, dataloader)
91
+ return {
92
+ "ddp": [ddp_model, ddp_dataloader, torch_device],
93
+ "no": [model, dataloader, accelerator.device],
94
+ }, accelerator
95
+
96
+
97
+ def generate_predictions(model, dataloader, accelerator):
98
+ logits_and_targets = []
99
+ for batch in dataloader:
100
+ input, target = batch.values()
101
+ with torch.no_grad():
102
+ logit = model(input)
103
+ logit, target = accelerator.gather_for_metrics((logit, target))
104
+ logits_and_targets.append((logit, target))
105
+ logits, targs = [], []
106
+ for logit, targ in logits_and_targets:
107
+ logits.append(logit)
108
+ targs.append(targ)
109
+ logits, targs = torch.cat(logits), torch.cat(targs)
110
+ return logits, targs
111
+
112
+
113
+ def test_torch_metrics(
114
+ accelerator: Accelerator, num_samples=82, dispatch_batches=False, split_batches=False, batch_size=16
115
+ ):
116
+ _, ddp_model, dataloader = get_basic_setup(accelerator, num_samples, batch_size)
117
+ logits, _ = generate_predictions(ddp_model, dataloader, accelerator)
118
+ assert len(logits) == num_samples, (
119
+ f"Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(logits)}"
120
+ )
121
+
122
+
123
+ def test_mrpc(dispatch_batches: bool = False, split_batches: bool = False):
124
+ metric = evaluate.load("glue", "mrpc")
125
+ setup, accelerator = get_mrpc_setup(dispatch_batches, split_batches)
126
+ # First do baseline
127
+ model, dataloader, device = setup["no"]
128
+ model.to(device)
129
+ model.eval()
130
+ for batch in dataloader:
131
+ batch.to(device)
132
+ with torch.inference_mode():
133
+ outputs = model(**batch)
134
+ preds = outputs.logits.argmax(dim=-1)
135
+ metric.add_batch(predictions=preds, references=batch["labels"])
136
+ baseline = metric.compute()
137
+
138
+ # Then do distributed
139
+ model, dataloader, device = setup["ddp"]
140
+ model.eval()
141
+ for batch in dataloader:
142
+ with torch.inference_mode():
143
+ outputs = model(**batch)
144
+ preds = outputs.logits.argmax(dim=-1)
145
+ references = batch["labels"]
146
+ preds, references = accelerator.gather_for_metrics((preds, references))
147
+ metric.add_batch(predictions=preds, references=references)
148
+ distributed = metric.compute()
149
+
150
+ for key in "accuracy f1".split():
151
+ assert math.isclose(baseline[key], distributed[key]), (
152
+ f"Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n"
153
+ )
154
+
155
+
156
+ def test_gather_for_metrics_with_non_tensor_objects_iterable_dataset():
157
+ class DummyIterableDataset(IterableDataset):
158
+ def __init__(self, data):
159
+ self.data = data
160
+
161
+ def __len__(self):
162
+ return len(self.data)
163
+
164
+ def __iter__(self):
165
+ yield from self.data
166
+
167
+ iterable_dataset = DummyIterableDataset([n for n in range(30)])
168
+ dataloader = DataLoader(iterable_dataset, batch_size=4)
169
+ accelerator = Accelerator()
170
+ prepared_dataloader = accelerator.prepare(dataloader)
171
+
172
+ if accelerator.is_main_process:
173
+ logger = logging.root.manager.loggerDict["accelerate.accelerator"]
174
+ list_handler = ListHandler()
175
+ logger.addHandler(list_handler)
176
+
177
+ batches_for_metrics = []
178
+ for batch in prepared_dataloader:
179
+ batches_for_metrics.append(accelerator.gather_for_metrics(batch))
180
+
181
+ assert torch.cat(batches_for_metrics).size(0) == 30
182
+
183
+ if accelerator.is_main_process:
184
+ assert len(list_handler.logs) == 0
185
+ logger.removeHandler(list_handler)
186
+
187
+
188
+ def test_gather_for_metrics_with_iterable_dataset():
189
+ class DummyIterableDataset(IterableDataset):
190
+ def __init__(self, data):
191
+ self.data = data
192
+
193
+ def __len__(self):
194
+ return len(self.data)
195
+
196
+ def __iter__(self):
197
+ yield from self.data
198
+
199
+ iterable_dataset = DummyIterableDataset(torch.as_tensor(range(30)))
200
+ dataloader = DataLoader(iterable_dataset, batch_size=4)
201
+
202
+ accelerator = Accelerator()
203
+ prepared_dataloader = accelerator.prepare(dataloader)
204
+
205
+ assert isinstance(prepared_dataloader, DataLoaderDispatcher)
206
+
207
+ if accelerator.is_main_process:
208
+ logger = logging.root.manager.loggerDict["accelerate.accelerator"]
209
+ list_handler = ListHandler()
210
+ logger.addHandler(list_handler)
211
+
212
+ batches_for_metrics = []
213
+ for batch in prepared_dataloader:
214
+ batches_for_metrics.append(accelerator.gather_for_metrics(batch))
215
+
216
+ assert torch.cat(batches_for_metrics).size(0) == 30
217
+
218
+ if accelerator.is_main_process:
219
+ assert len(list_handler.logs) == 0
220
+
221
+ logger.removeHandler(list_handler)
222
+
223
+
224
+ def test_gather_for_metrics_drop_last():
225
+ accelerator = Accelerator()
226
+ per_device_batch_size = 5
227
+ num_items = (10 * accelerator.num_processes) + 1
228
+ dataloader = DataLoader(range(num_items), batch_size=per_device_batch_size, drop_last=True)
229
+ dataloader = accelerator.prepare(dataloader)
230
+
231
+ iterator = iter(dataloader)
232
+ next(iterator) # Skip first batch tensor([0, 1, 2, 3, 4], device='cuda:0')
233
+ batch = next(iterator)
234
+ gathered_items = accelerator.gather_for_metrics(batch)
235
+
236
+ # Should return a full set of complete batches from each GPU
237
+ num_expected_items = per_device_batch_size * accelerator.num_processes
238
+ assert gathered_items.size(0) == (num_expected_items), (
239
+ f"Expected number of items: {num_expected_items}, Actual: {gathered_items.size(0)}"
240
+ )
241
+
242
+
243
+ def main():
244
+ dataloader_config = DataLoaderConfiguration(split_batches=False, dispatch_batches=False)
245
+ accelerator = Accelerator(dataloader_config=dataloader_config)
246
+ if accelerator.is_local_main_process:
247
+ datasets.utils.logging.set_verbosity_warning()
248
+ transformers.utils.logging.set_verbosity_warning()
249
+ else:
250
+ datasets.utils.logging.set_verbosity_error()
251
+ transformers.utils.logging.set_verbosity_error()
252
+ # TorchXLA does not support batch dispatching. 'put_on_device' is always False for
253
+ # TorchXLA, which can cause a value error in 'prepare_data_loader' function.
254
+ dispatch_batches_options = [False] if accelerator.state.distributed_type == DistributedType.XLA else [True, False]
255
+
256
+ # Temporarily close this test for TorchXLA due to the 'Cannot set version_counter for
257
+ # inference tensor' error in inference mode. Reopen it after TorchXLA fixes this bug.
258
+ # These are a bit slower so they should only be ran on the GPU or TPU
259
+ if accelerator.device.type != "cpu" and not is_torch_xla_available():
260
+ if accelerator.is_local_main_process:
261
+ print("**Testing gather_for_metrics**")
262
+ for split_batches in [True, False]:
263
+ for dispatch_batches in dispatch_batches_options:
264
+ if accelerator.is_local_main_process:
265
+ print(f"With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`")
266
+ test_mrpc(dispatch_batches, split_batches)
267
+ accelerator.state._reset_state()
268
+ print("test_gather_for_metrics_with_iterable_dataset")
269
+ test_gather_for_metrics_with_iterable_dataset()
270
+ print("test gather_for_metrics_with_non_tensor_objects_iterable_dataset")
271
+ test_gather_for_metrics_with_non_tensor_objects_iterable_dataset()
272
+
273
+ # MpDeviceLoader in TorchXLA is an asynchronous loader that preloads several batches into cache.
274
+ # This can cause the 'end_of_dataloader' of DataLoaderStateMixin to be set earlier than intended.
275
+ # Skip this test when TorchXLA is enabled.
276
+ if accelerator.state.distributed_type != DistributedType.XLA:
277
+ if accelerator.is_local_main_process:
278
+ print("**Test torch metrics**")
279
+ for split_batches in [True, False]:
280
+ for dispatch_batches in dispatch_batches_options:
281
+ dataloader_config = DataLoaderConfiguration(
282
+ split_batches=split_batches, dispatch_batches=dispatch_batches
283
+ )
284
+ accelerator = Accelerator(dataloader_config=dataloader_config)
285
+ if accelerator.is_local_main_process:
286
+ print(f"With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99")
287
+ test_torch_metrics(accelerator, 99)
288
+ accelerator.state._reset_state()
289
+ if accelerator.is_local_main_process:
290
+ print("**Test last batch is not dropped when perfectly divisible**")
291
+ accelerator = Accelerator()
292
+ test_torch_metrics(accelerator, 512)
293
+ accelerator.state._reset_state()
294
+ if accelerator.is_local_main_process:
295
+ print("**Test that `drop_last` is taken into account**")
296
+ test_gather_for_metrics_drop_last()
297
+ accelerator.end_training()
298
+ accelerator.state._reset_state()
299
+
300
+
301
+ def _mp_fn(index):
302
+ # For xla_spawn (TPUs)
303
+ main()
304
+
305
+
306
+ if __name__ == "__main__":
307
+ main()
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/test_peak_memory_usage.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import argparse
15
+ import gc
16
+ import json
17
+ import os
18
+
19
+ import torch
20
+ from datasets import load_dataset
21
+ from torch.optim import AdamW
22
+ from torch.utils.data import DataLoader
23
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
24
+
25
+ from accelerate import Accelerator, DistributedType
26
+ from accelerate.utils import (
27
+ is_hpu_available,
28
+ is_mlu_available,
29
+ is_musa_available,
30
+ is_npu_available,
31
+ is_sdaa_available,
32
+ is_xpu_available,
33
+ )
34
+ from accelerate.utils.deepspeed import DummyOptim, DummyScheduler
35
+
36
+
37
+ MAX_GPU_BATCH_SIZE = 16
38
+ EVAL_BATCH_SIZE = 32
39
+
40
+
41
+ # Converting Bytes to Megabytes
42
+ def b2mb(x):
43
+ return int(x / 2**20)
44
+
45
+
46
+ # This context manager is used to track the peak memory usage of the process
47
+ class TorchTracemalloc:
48
+ def __enter__(self):
49
+ gc.collect()
50
+ if torch.cuda.is_available():
51
+ torch.cuda.empty_cache()
52
+ torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero
53
+ self.begin = torch.cuda.memory_allocated()
54
+ elif is_mlu_available():
55
+ torch.mlu.empty_cache()
56
+ torch.mlu.reset_max_memory_allocated() # reset the peak gauge to zero
57
+ self.begin = torch.mlu.memory_allocated()
58
+ elif is_sdaa_available():
59
+ torch.sdaa.empty_cache()
60
+ torch.sdaa.reset_max_memory_allocated() # reset the peak gauge to zero
61
+ self.begin = torch.sdaa.memory_allocated()
62
+ elif is_musa_available():
63
+ torch.musa.empty_cache()
64
+ torch.musa.reset_max_memory_allocated() # reset the peak gauge to zero
65
+ self.begin = torch.musa.memory_allocated()
66
+ elif is_npu_available():
67
+ torch.npu.empty_cache()
68
+ torch.npu.reset_max_memory_allocated() # reset the peak gauge to zero
69
+ self.begin = torch.npu.memory_allocated()
70
+ elif is_xpu_available():
71
+ torch.xpu.empty_cache()
72
+ torch.xpu.reset_max_memory_allocated() # reset the peak gauge to zero
73
+ self.begin = torch.xpu.memory_allocated()
74
+ elif is_hpu_available():
75
+ # torch.hpu.empty_cache() # not available on hpu as it reserves all device memory for the current process
76
+ torch.hpu.reset_peak_memory_stats() # reset the peak gauge to zero
77
+ self.begin = torch.hpu.memory_allocated()
78
+ return self
79
+
80
+ def __exit__(self, *exc):
81
+ gc.collect()
82
+ if torch.cuda.is_available():
83
+ torch.cuda.empty_cache()
84
+ self.end = torch.cuda.memory_allocated()
85
+ self.peak = torch.cuda.max_memory_allocated()
86
+ elif is_mlu_available():
87
+ torch.mlu.empty_cache()
88
+ self.end = torch.mlu.memory_allocated()
89
+ self.begin = torch.mlu.max_memory_allocated()
90
+ elif is_sdaa_available():
91
+ torch.sdaa.empty_cache()
92
+ self.end = torch.sdaa.memory_allocated()
93
+ self.begin = torch.sdaa.max_memory_allocated()
94
+ elif is_musa_available():
95
+ torch.musa.empty_cache()
96
+ self.end = torch.musa.memory_allocated()
97
+ self.begin = torch.musa.max_memory_allocated()
98
+ elif is_npu_available():
99
+ torch.npu.empty_cache()
100
+ self.end = torch.npu.memory_allocated()
101
+ self.peak = torch.npu.max_memory_allocated()
102
+ elif is_xpu_available():
103
+ torch.xpu.empty_cache()
104
+ self.end = torch.xpu.memory_allocated()
105
+ self.peak = torch.xpu.max_memory_allocated()
106
+ elif is_hpu_available():
107
+ # torch.hpu.empty_cache() # not available on hpu as it reserves all device memory for the current process
108
+ self.end = torch.hpu.memory_allocated()
109
+ self.peak = torch.hpu.max_memory_allocated()
110
+ self.used = b2mb(self.end - self.begin)
111
+ self.peaked = b2mb(self.peak - self.begin)
112
+ # print(f"delta used/peak {self.used:4d}/{self.peaked:4d}")
113
+
114
+
115
+ def get_dataloaders(
116
+ accelerator: Accelerator,
117
+ batch_size: int = 16,
118
+ model_name: str = "bert-base-cased",
119
+ n_train: int = 320,
120
+ n_val: int = 160,
121
+ ):
122
+ """
123
+ Creates a set of `DataLoader`s for the `glue` dataset.
124
+
125
+ Args:
126
+ accelerator (`Accelerator`):
127
+ An `Accelerator` object
128
+ batch_size (`int`, *optional*):
129
+ The batch size for the train and validation DataLoaders.
130
+ model_name (`str`, *optional*):
131
+ The name of the model to use.
132
+ n_train (`int`, *optional*):
133
+ The number of training examples to use.
134
+ n_val (`int`, *optional*):
135
+ The number of validation examples to use.
136
+ """
137
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
138
+ datasets = load_dataset(
139
+ "glue", "mrpc", split={"train": f"train[:{n_train}]", "validation": f"validation[:{n_val}]"}
140
+ )
141
+
142
+ def tokenize_function(examples):
143
+ # max_length=None => use the model max length (it's actually the default)
144
+ outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
145
+ return outputs
146
+
147
+ # Apply the method we just defined to all the examples in all the splits of the dataset
148
+ tokenized_datasets = datasets.map(
149
+ tokenize_function, batched=True, remove_columns=["idx", "sentence1", "sentence2"], load_from_cache_file=False
150
+ )
151
+
152
+ # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
153
+ # transformers library
154
+ tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
155
+
156
+ def collate_fn(examples):
157
+ # On TPU it's best to pad everything to the same length or training will be very slow.
158
+ if accelerator.distributed_type == DistributedType.XLA:
159
+ return tokenizer.pad(examples, padding="max_length", max_length=128, return_tensors="pt")
160
+ return tokenizer.pad(examples, padding="longest", return_tensors="pt")
161
+
162
+ # Instantiate dataloaders.
163
+ train_dataloader = DataLoader(
164
+ tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
165
+ )
166
+ eval_dataloader = DataLoader(
167
+ tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
168
+ )
169
+
170
+ return train_dataloader, eval_dataloader
171
+
172
+
173
+ def training_function(config, args):
174
+ # Initialize accelerator
175
+ accelerator = Accelerator()
176
+
177
+ # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
178
+ lr = config["lr"]
179
+ num_epochs = int(config["num_epochs"])
180
+ seed = int(config["seed"])
181
+ batch_size = int(config["batch_size"])
182
+ model_name = args.model_name_or_path
183
+
184
+ set_seed(seed)
185
+ train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size, model_name, args.n_train, args.n_val)
186
+
187
+ # Instantiate the model (we build the model here so that the seed also control new weights initialization)
188
+ model = AutoModelForSequenceClassification.from_pretrained(model_name, return_dict=True)
189
+
190
+ # Instantiate optimizer
191
+ optimizer_cls = (
192
+ AdamW
193
+ if accelerator.state.deepspeed_plugin is None
194
+ or "optimizer" not in accelerator.state.deepspeed_plugin.deepspeed_config
195
+ else DummyOptim
196
+ )
197
+ optimizer = optimizer_cls(params=model.parameters(), lr=lr)
198
+
199
+ if accelerator.state.deepspeed_plugin is not None:
200
+ gradient_accumulation_steps = accelerator.state.deepspeed_plugin.deepspeed_config[
201
+ "gradient_accumulation_steps"
202
+ ]
203
+ else:
204
+ gradient_accumulation_steps = 1
205
+ max_training_steps = (len(train_dataloader) * num_epochs) // gradient_accumulation_steps
206
+
207
+ # Instantiate scheduler
208
+ if (
209
+ accelerator.state.deepspeed_plugin is None
210
+ or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config
211
+ ):
212
+ lr_scheduler = get_linear_schedule_with_warmup(
213
+ optimizer=optimizer,
214
+ num_warmup_steps=0,
215
+ num_training_steps=max_training_steps,
216
+ )
217
+ else:
218
+ lr_scheduler = DummyScheduler(optimizer, total_num_steps=max_training_steps, warmup_num_steps=0)
219
+
220
+ # Prepare everything
221
+ # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
222
+ # prepare method.
223
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
224
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
225
+ )
226
+
227
+ # We need to keep track of how many total steps we have iterated over
228
+ overall_step = 0
229
+ # We also need to keep track of the stating epoch so files are named properly
230
+ starting_epoch = 0
231
+
232
+ # Now we train the model
233
+ train_total_peak_memory = {}
234
+ for epoch in range(starting_epoch, num_epochs):
235
+ with TorchTracemalloc() as tracemalloc:
236
+ model.train()
237
+ for step, batch in enumerate(train_dataloader):
238
+ outputs = model(**batch)
239
+ loss = outputs.loss
240
+ loss = loss / gradient_accumulation_steps
241
+ accelerator.backward(loss)
242
+ if step % gradient_accumulation_steps == 0:
243
+ optimizer.step()
244
+ lr_scheduler.step()
245
+ optimizer.zero_grad()
246
+
247
+ overall_step += 1
248
+
249
+ # Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage
250
+ accelerator.print(f"Memory before entering the train : {b2mb(tracemalloc.begin)}")
251
+ accelerator.print(f"Memory consumed at the end of the train (end-begin): {tracemalloc.used}")
252
+ accelerator.print(f"Peak Memory consumed during the train (max-begin): {tracemalloc.peaked}")
253
+ accelerator.print(
254
+ f"Total Peak Memory consumed during the train (max): {tracemalloc.peaked + b2mb(tracemalloc.begin)}"
255
+ )
256
+ train_total_peak_memory[f"epoch-{epoch}"] = tracemalloc.peaked + b2mb(tracemalloc.begin)
257
+ if args.peak_memory_upper_bound is not None:
258
+ assert train_total_peak_memory[f"epoch-{epoch}"] <= args.peak_memory_upper_bound, (
259
+ "Peak memory usage exceeded the upper bound"
260
+ )
261
+
262
+ accelerator.wait_for_everyone()
263
+ if accelerator.is_main_process:
264
+ with open(os.path.join(args.output_dir, "peak_memory_utilization.json"), "w") as f:
265
+ json.dump(train_total_peak_memory, f)
266
+ accelerator.end_training()
267
+
268
+
269
+ def main():
270
+ parser = argparse.ArgumentParser(description="Simple example of training script tracking peak GPU memory usage.")
271
+ parser.add_argument(
272
+ "--model_name_or_path",
273
+ type=str,
274
+ default="bert-base-cased",
275
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
276
+ required=False,
277
+ )
278
+ parser.add_argument(
279
+ "--output_dir",
280
+ type=str,
281
+ default=".",
282
+ help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory.",
283
+ )
284
+ parser.add_argument(
285
+ "--peak_memory_upper_bound",
286
+ type=float,
287
+ default=None,
288
+ help="The upper bound of peak memory usage in MB. If set, the training will throw an error if the peak memory usage exceeds this value.",
289
+ )
290
+ parser.add_argument(
291
+ "--n_train",
292
+ type=int,
293
+ default=320,
294
+ help="Number of training examples to use.",
295
+ )
296
+ parser.add_argument(
297
+ "--n_val",
298
+ type=int,
299
+ default=160,
300
+ help="Number of validation examples to use.",
301
+ )
302
+ parser.add_argument(
303
+ "--num_epochs",
304
+ type=int,
305
+ default=1,
306
+ help="Number of train epochs.",
307
+ )
308
+ args = parser.parse_args()
309
+ config = {"lr": 2e-5, "num_epochs": args.num_epochs, "seed": 42, "batch_size": 16}
310
+ training_function(config, args)
311
+
312
+
313
+ if __name__ == "__main__":
314
+ main()
tasks/tasksmith-b1dd32dfa88b/tests/source/src/accelerate/test_utils/scripts/external_deps/test_performance.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import argparse
15
+ import json
16
+ import os
17
+ from contextlib import nullcontext
18
+ from pathlib import Path
19
+
20
+ import evaluate
21
+ import torch
22
+ from datasets import load_dataset
23
+ from torch.optim import AdamW
24
+ from torch.utils.data import DataLoader
25
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup
26
+
27
+ from accelerate import Accelerator, DistributedType
28
+ from accelerate.parallelism_config import ParallelismConfig
29
+ from accelerate.utils import SAFE_WEIGHTS_NAME, set_seed
30
+ from accelerate.utils.deepspeed import DummyOptim, DummyScheduler
31
+
32
+
33
+ MAX_GPU_BATCH_SIZE = 16
34
+ EVAL_BATCH_SIZE = 32
35
+
36
+
37
+ def get_dataloaders(accelerator: Accelerator, batch_size: int = 16, model_name: str = "bert-base-cased"):
38
+ """
39
+ Creates a set of `DataLoader`s for the `glue` dataset.
40
+
41
+ Args:
42
+ accelerator (`Accelerator`):
43
+ An `Accelerator` object
44
+ batch_size (`int`, *optional*):
45
+ The batch size for the train and validation DataLoaders.
46
+ model_name (`str`, *optional*):
47
+ """
48
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
49
+
50
+ datasets = load_dataset("glue", "mrpc")
51
+
52
+ def tokenize_function(examples):
53
+ # max_length=None => use the model max length (it's actually the default)
54
+ outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
55
+ return outputs
56
+
57
+ # Apply the method we just defined to all the examples in all the splits of the dataset
58
+ tokenized_datasets = datasets.map(
59
+ tokenize_function, batched=True, remove_columns=["idx", "sentence1", "sentence2"], load_from_cache_file=False
60
+ )
61
+
62
+ # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
63
+ # transformers library
64
+ tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
65
+
66
+ def collate_fn(examples):
67
+ # On TPU it's best to pad everything to the same length or training will be very slow.
68
+ if accelerator.distributed_type == DistributedType.XLA:
69
+ return tokenizer.pad(examples, padding="max_length", max_length=128, return_tensors="pt")
70
+ return tokenizer.pad(examples, padding="longest", return_tensors="pt")
71
+
72
+ # Instantiate dataloaders.
73
+ train_dataloader = DataLoader(
74
+ tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
75
+ )
76
+ eval_dataloader = DataLoader(
77
+ tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
78
+ )
79
+
80
+ return train_dataloader, eval_dataloader
81
+
82
+
83
+ def training_function(config, args):
84
+ accelerator_kwargs = {}
85
+ # need this for DeepSpeed tests as `args.tp_size` would be None and `torch.distributed.init_device_mesh` would fail
86
+ if args.tp_size is not None:
87
+ accelerator_kwargs["parallelism_config"] = ParallelismConfig(tp_size=args.tp_size)
88
+
89
+ # Initialize accelerator
90
+ accelerator = Accelerator(**accelerator_kwargs)
91
+
92
+ # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
93
+ lr = config["lr"]
94
+ num_epochs = int(config["num_epochs"])
95
+ seed = int(config["seed"])
96
+ batch_size = int(config["batch_size"])
97
+ model_name = args.model_name_or_path
98
+
99
+ set_seed(seed)
100
+ train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size, model_name)
101
+
102
+ # Add TP related kwargs if provided
103
+ model_kwargs = {}
104
+ if args.tp_plan is not None:
105
+ model_kwargs["tp_plan"] = args.tp_plan
106
+ if args.tp_size is not None:
107
+ model_kwargs["tp_size"] = args.tp_size
108
+
109
+ # Instantiate the model (we build the model here so that the seed also control new weights initialization)
110
+ model = AutoModelForSequenceClassification.from_pretrained(model_name, return_dict=True, **model_kwargs)
111
+
112
+ if args.add_pad_token:
113
+ if model.config.pad_token_id is None:
114
+ model.config.pad_token_id = 0
115
+
116
+ # Instantiate optimizer
117
+ optimizer_cls = (
118
+ AdamW
119
+ if accelerator.state.deepspeed_plugin is None
120
+ or "optimizer" not in accelerator.state.deepspeed_plugin.deepspeed_config
121
+ else DummyOptim
122
+ )
123
+ optimizer = optimizer_cls(params=model.parameters(), lr=lr)
124
+
125
+ max_training_steps = len(train_dataloader) * num_epochs
126
+
127
+ # Instantiate scheduler
128
+ linear_decay_scheduler = False
129
+ if (
130
+ accelerator.state.deepspeed_plugin is None
131
+ or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config
132
+ ):
133
+ lr_scheduler = get_linear_schedule_with_warmup(
134
+ optimizer=optimizer,
135
+ num_warmup_steps=0,
136
+ num_training_steps=max_training_steps,
137
+ )
138
+ linear_decay_scheduler = True
139
+ else:
140
+ lr_scheduler = DummyScheduler(optimizer, total_num_steps=max_training_steps, warmup_num_steps=0)
141
+
142
+ # Prepare everything
143
+ # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
144
+ # prepare method.
145
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
146
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
147
+ )
148
+
149
+ # We also need to keep track of the stating epoch so files are named properly
150
+ starting_epoch = 0
151
+
152
+ # Now we train the model
153
+ metric = evaluate.load("glue", "mrpc")
154
+ best_performance = 0
155
+ performance_metric = {}
156
+ expected_lr_after_first_optim_step = lr * (
157
+ 1 - 1 / (max_training_steps / accelerator.num_processes / accelerator.gradient_accumulation_steps)
158
+ )
159
+ lr_scheduler_check_completed = False
160
+ for epoch in range(starting_epoch, num_epochs):
161
+ model.train()
162
+ for step, batch in enumerate(train_dataloader):
163
+ with accelerator.accumulate(model):
164
+ outputs = model(**batch)
165
+ loss = outputs.loss
166
+ accelerator.backward(loss)
167
+ context = nullcontext
168
+ if args.tp_plan is not None:
169
+ from torch.distributed._tensor.experimental import implicit_replication
170
+
171
+ context = implicit_replication
172
+ with context():
173
+ optimizer.step()
174
+ lr_scheduler.step()
175
+ optimizer.zero_grad()
176
+
177
+ # assert the learning rate after first optimizer step
178
+ if (
179
+ accelerator.sync_gradients
180
+ and not lr_scheduler_check_completed
181
+ and linear_decay_scheduler
182
+ and accelerator.state.mixed_precision == "no"
183
+ ):
184
+ assert lr_scheduler.get_last_lr()[0] == expected_lr_after_first_optim_step, (
185
+ f"Wrong lr found at second step, expected {expected_lr_after_first_optim_step}, got {lr_scheduler.get_last_lr()[0]}"
186
+ )
187
+ lr_scheduler_check_completed = True
188
+
189
+ model.eval()
190
+ samples_seen = 0
191
+ for step, batch in enumerate(eval_dataloader):
192
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
193
+ batch.to(accelerator.device)
194
+ with torch.no_grad():
195
+ outputs = model(**batch)
196
+ predictions = outputs.logits.argmax(dim=-1)
197
+ # It is slightly faster to call this once, than multiple times
198
+ predictions, references = accelerator.gather(
199
+ (predictions, batch["labels"])
200
+ ) # If we are in a multiprocess environment, the last batch has duplicates
201
+ if accelerator.use_distributed:
202
+ if step == len(eval_dataloader) - 1:
203
+ predictions = predictions[: len(eval_dataloader.dataset) - samples_seen]
204
+ references = references[: len(eval_dataloader.dataset) - samples_seen]
205
+ else:
206
+ samples_seen += references.shape[0]
207
+ metric.add_batch(
208
+ predictions=predictions,
209
+ references=references,
210
+ )
211
+
212
+ eval_metric = metric.compute()
213
+ # Use accelerator.print to print only on the main process.
214
+ accelerator.print(f"epoch {epoch}:", eval_metric)
215
+ performance_metric[f"epoch-{epoch}"] = eval_metric["accuracy"]
216
+
217
+ if best_performance < eval_metric["accuracy"]:
218
+ best_performance = eval_metric["accuracy"]
219
+
220
+ # check that the LR is 0
221
+ if linear_decay_scheduler and accelerator.state.mixed_precision == "no":
222
+ assert lr_scheduler.get_last_lr()[0] == 0, (
223
+ f"Wrong lr found at last step, expected 0, got {lr_scheduler.get_last_lr()[0]}"
224
+ )
225
+
226
+ if args.performance_lower_bound is not None:
227
+ assert args.performance_lower_bound <= best_performance, (
228
+ f"Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}"
229
+ )
230
+
231
+ accelerator.wait_for_everyone()
232
+ if accelerator.is_main_process:
233
+ with open(os.path.join(args.output_dir, "all_results.json"), "w") as f:
234
+ json.dump(performance_metric, f)
235
+
236
+ # TODO: skip saving of the model test for TP until the feature lands
237
+ if args.tp_plan is None:
238
+ # Finally try saving the model
239
+ accelerator.save_model(model, args.output_dir)
240
+ accelerator.wait_for_everyone()
241
+ if args.tp_plan is None:
242
+ assert Path(args.output_dir, SAFE_WEIGHTS_NAME).exists(), (
243
+ "Model was not saved when calling `Accelerator.save_model`"
244
+ )
245
+ accelerator.end_training()
246
+
247
+
248
+ def main():
249
+ parser = argparse.ArgumentParser(description="Simple example of training script tracking peak GPU memory usage.")
250
+ parser.add_argument(
251
+ "--model_name_or_path",
252
+ type=str,
253
+ default="bert-base-cased",
254
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
255
+ required=False,
256
+ )
257
+ parser.add_argument(
258
+ "--output_dir",
259
+ type=str,
260
+ default=".",
261
+ help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory.",
262
+ )
263
+ parser.add_argument(
264
+ "--performance_lower_bound",
265
+ type=float,
266
+ default=None,
267
+ help="Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.",
268
+ )
269
+ parser.add_argument(
270
+ "--num_epochs",
271
+ type=int,
272
+ default=3,
273
+ help="Number of train epochs.",
274
+ )
275
+ parser.add_argument(
276
+ "--add_pad_token",
277
+ type=bool,
278
+ default=False,
279
+ help="To add pad token if not exists.",
280
+ )
281
+ parser.add_argument(
282
+ "--tp_plan",
283
+ type=str,
284
+ default=None,
285
+ help="pass 'auto' to use TP",
286
+ )
287
+ parser.add_argument(
288
+ "--tp_size",
289
+ type=int,
290
+ default=None,
291
+ help="TP size to be used to shard the model",
292
+ )
293
+ args = parser.parse_args()
294
+ config = {"lr": 2e-5, "num_epochs": args.num_epochs, "seed": 42, "batch_size": 16}
295
+ training_function(config, args)
296
+
297
+
298
+ if __name__ == "__main__":
299
+ main()