SuperRealCo commited on
Commit
bbb06b1
·
verified ·
1 Parent(s): d95e807

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +3 -0
  2. venv/lib/python3.10/site-packages/accelerate/__pycache__/accelerator.cpython-310.pyc +3 -0
  3. venv/lib/python3.10/site-packages/accelerate/commands/__init__.py +13 -0
  4. venv/lib/python3.10/site-packages/accelerate/commands/__pycache__/__init__.cpython-310.pyc +0 -0
  5. venv/lib/python3.10/site-packages/accelerate/commands/__pycache__/accelerate_cli.cpython-310.pyc +0 -0
  6. venv/lib/python3.10/site-packages/accelerate/commands/__pycache__/env.cpython-310.pyc +0 -0
  7. venv/lib/python3.10/site-packages/accelerate/commands/__pycache__/estimate.cpython-310.pyc +0 -0
  8. venv/lib/python3.10/site-packages/accelerate/commands/__pycache__/launch.cpython-310.pyc +0 -0
  9. venv/lib/python3.10/site-packages/accelerate/commands/__pycache__/merge.cpython-310.pyc +0 -0
  10. venv/lib/python3.10/site-packages/accelerate/commands/__pycache__/test.cpython-310.pyc +0 -0
  11. venv/lib/python3.10/site-packages/accelerate/commands/__pycache__/to_fsdp2.cpython-310.pyc +0 -0
  12. venv/lib/python3.10/site-packages/accelerate/commands/__pycache__/tpu.cpython-310.pyc +0 -0
  13. venv/lib/python3.10/site-packages/accelerate/commands/__pycache__/utils.cpython-310.pyc +0 -0
  14. venv/lib/python3.10/site-packages/accelerate/commands/accelerate_cli.py +54 -0
  15. venv/lib/python3.10/site-packages/accelerate/commands/config/__init__.py +52 -0
  16. venv/lib/python3.10/site-packages/accelerate/commands/config/__pycache__/__init__.cpython-310.pyc +0 -0
  17. venv/lib/python3.10/site-packages/accelerate/commands/config/__pycache__/cluster.cpython-310.pyc +0 -0
  18. venv/lib/python3.10/site-packages/accelerate/commands/config/__pycache__/config.cpython-310.pyc +0 -0
  19. venv/lib/python3.10/site-packages/accelerate/commands/config/__pycache__/config_args.cpython-310.pyc +0 -0
  20. venv/lib/python3.10/site-packages/accelerate/commands/config/__pycache__/config_utils.cpython-310.pyc +0 -0
  21. venv/lib/python3.10/site-packages/accelerate/commands/config/__pycache__/default.cpython-310.pyc +0 -0
  22. venv/lib/python3.10/site-packages/accelerate/commands/config/__pycache__/sagemaker.cpython-310.pyc +0 -0
  23. venv/lib/python3.10/site-packages/accelerate/commands/config/__pycache__/update.cpython-310.pyc +0 -0
  24. venv/lib/python3.10/site-packages/accelerate/commands/config/cluster.py +869 -0
  25. venv/lib/python3.10/site-packages/accelerate/commands/config/config.py +89 -0
  26. venv/lib/python3.10/site-packages/accelerate/commands/config/config_args.py +252 -0
  27. venv/lib/python3.10/site-packages/accelerate/commands/config/config_utils.py +122 -0
  28. venv/lib/python3.10/site-packages/accelerate/commands/config/default.py +163 -0
  29. venv/lib/python3.10/site-packages/accelerate/commands/config/sagemaker.py +274 -0
  30. venv/lib/python3.10/site-packages/accelerate/commands/config/update.py +63 -0
  31. venv/lib/python3.10/site-packages/accelerate/commands/env.py +131 -0
  32. venv/lib/python3.10/site-packages/accelerate/commands/estimate.py +312 -0
  33. venv/lib/python3.10/site-packages/accelerate/commands/launch.py +1209 -0
  34. venv/lib/python3.10/site-packages/accelerate/commands/menu/__init__.py +14 -0
  35. venv/lib/python3.10/site-packages/accelerate/commands/menu/__pycache__/__init__.cpython-310.pyc +0 -0
  36. venv/lib/python3.10/site-packages/accelerate/commands/menu/__pycache__/cursor.cpython-310.pyc +0 -0
  37. venv/lib/python3.10/site-packages/accelerate/commands/menu/__pycache__/helpers.cpython-310.pyc +0 -0
  38. venv/lib/python3.10/site-packages/accelerate/commands/menu/__pycache__/input.cpython-310.pyc +0 -0
  39. venv/lib/python3.10/site-packages/accelerate/commands/menu/__pycache__/keymap.cpython-310.pyc +0 -0
  40. venv/lib/python3.10/site-packages/accelerate/commands/menu/__pycache__/selection_menu.cpython-310.pyc +0 -0
  41. venv/lib/python3.10/site-packages/accelerate/commands/menu/cursor.py +65 -0
  42. venv/lib/python3.10/site-packages/accelerate/commands/menu/helpers.py +59 -0
  43. venv/lib/python3.10/site-packages/accelerate/commands/menu/input.py +84 -0
  44. venv/lib/python3.10/site-packages/accelerate/commands/menu/keymap.py +133 -0
  45. venv/lib/python3.10/site-packages/accelerate/commands/menu/selection_menu.py +144 -0
  46. venv/lib/python3.10/site-packages/accelerate/commands/merge.py +69 -0
  47. venv/lib/python3.10/site-packages/accelerate/commands/test.py +65 -0
  48. venv/lib/python3.10/site-packages/accelerate/commands/to_fsdp2.py +172 -0
  49. venv/lib/python3.10/site-packages/accelerate/commands/tpu.py +157 -0
  50. venv/lib/python3.10/site-packages/accelerate/commands/utils.py +123 -0
.gitattributes CHANGED
@@ -72,3 +72,6 @@ venv/lib/python3.10/site-packages/wrapt/_wrappers.cpython-310-x86_64-linux-gnu.s
72
  venv/lib/python3.10/site-packages/diffusers/models/__pycache__/attention_processor.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
73
  venv/lib/python3.10/site-packages/accelerate/utils/__pycache__/dataclasses.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
74
  venv/lib/python3.10/site-packages/diffusers/loaders/__pycache__/lora_pipeline.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
 
 
 
 
72
  venv/lib/python3.10/site-packages/diffusers/models/__pycache__/attention_processor.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
73
  venv/lib/python3.10/site-packages/accelerate/utils/__pycache__/dataclasses.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
74
  venv/lib/python3.10/site-packages/diffusers/loaders/__pycache__/lora_pipeline.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
75
+ venv/lib/python3.10/site-packages/accelerate/__pycache__/accelerator.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
76
+ venv/lib/python3.10/site-packages/deepspeed/runtime/__pycache__/engine.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
77
+ venv/lib/python3.10/site-packages/hf_transfer/hf_transfer.abi3.so filter=lfs diff=lfs merge=lfs -text
venv/lib/python3.10/site-packages/accelerate/__pycache__/accelerator.cpython-310.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c005c697ef0add5080c18e222594cb3e894ade8e7a6e30d27b2365127f090b9b
3
+ size 126436
venv/lib/python3.10/site-packages/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.
venv/lib/python3.10/site-packages/accelerate/commands/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (177 Bytes). View file
 
venv/lib/python3.10/site-packages/accelerate/commands/__pycache__/accelerate_cli.cpython-310.pyc ADDED
Binary file (1.39 kB). View file
 
venv/lib/python3.10/site-packages/accelerate/commands/__pycache__/env.cpython-310.pyc ADDED
Binary file (3.22 kB). View file
 
venv/lib/python3.10/site-packages/accelerate/commands/__pycache__/estimate.cpython-310.pyc ADDED
Binary file (10.2 kB). View file
 
venv/lib/python3.10/site-packages/accelerate/commands/__pycache__/launch.cpython-310.pyc ADDED
Binary file (32 kB). View file
 
venv/lib/python3.10/site-packages/accelerate/commands/__pycache__/merge.cpython-310.pyc ADDED
Binary file (1.84 kB). View file
 
venv/lib/python3.10/site-packages/accelerate/commands/__pycache__/test.cpython-310.pyc ADDED
Binary file (1.64 kB). View file
 
venv/lib/python3.10/site-packages/accelerate/commands/__pycache__/to_fsdp2.cpython-310.pyc ADDED
Binary file (4.09 kB). View file
 
venv/lib/python3.10/site-packages/accelerate/commands/__pycache__/tpu.cpython-310.pyc ADDED
Binary file (3.84 kB). View file
 
venv/lib/python3.10/site-packages/accelerate/commands/__pycache__/utils.cpython-310.pyc ADDED
Binary file (3.78 kB). View file
 
venv/lib/python3.10/site-packages/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()
venv/lib/python3.10/site-packages/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()
venv/lib/python3.10/site-packages/accelerate/commands/config/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.08 kB). View file
 
venv/lib/python3.10/site-packages/accelerate/commands/config/__pycache__/cluster.cpython-310.pyc ADDED
Binary file (18.5 kB). View file
 
venv/lib/python3.10/site-packages/accelerate/commands/config/__pycache__/config.cpython-310.pyc ADDED
Binary file (2.43 kB). View file
 
venv/lib/python3.10/site-packages/accelerate/commands/config/__pycache__/config_args.cpython-310.pyc ADDED
Binary file (7.35 kB). View file
 
venv/lib/python3.10/site-packages/accelerate/commands/config/__pycache__/config_utils.cpython-310.pyc ADDED
Binary file (2.99 kB). View file
 
venv/lib/python3.10/site-packages/accelerate/commands/config/__pycache__/default.cpython-310.pyc ADDED
Binary file (4.21 kB). View file
 
venv/lib/python3.10/site-packages/accelerate/commands/config/__pycache__/sagemaker.cpython-310.pyc ADDED
Binary file (6.98 kB). View file
 
venv/lib/python3.10/site-packages/accelerate/commands/config/__pycache__/update.cpython-310.pyc ADDED
Binary file (1.85 kB). View file
 
venv/lib/python3.10/site-packages/accelerate/commands/config/cluster.py ADDED
@@ -0,0 +1,869 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ megatron_lm_config = {}
509
+ if distributed_type in [DistributedType.MULTI_GPU]:
510
+ use_megatron_lm = _ask_field(
511
+ "Do you want to use Megatron-LM ? [yes/NO]: ",
512
+ _convert_yes_no_to_bool,
513
+ default=False,
514
+ error_message="Please enter yes or no.",
515
+ )
516
+ if use_megatron_lm:
517
+ distributed_type = DistributedType.MEGATRON_LM
518
+ if distributed_type == DistributedType.MEGATRON_LM:
519
+ prefix = "megatron_lm_"
520
+ megatron_lm_config[prefix + "tp_degree"] = _ask_field(
521
+ "What is the Tensor Parallelism degree/size? [1]:",
522
+ int,
523
+ default=1,
524
+ error_message="Please enter an integer.",
525
+ )
526
+ if megatron_lm_config[prefix + "tp_degree"] > 1:
527
+ megatron_lm_config[prefix + "sequence_parallelism"] = _ask_field(
528
+ "Do you want to enable Sequence Parallelism? [YES/no]: ",
529
+ _convert_yes_no_to_bool,
530
+ default=True,
531
+ error_message="Please enter yes or no.",
532
+ )
533
+
534
+ megatron_lm_config[prefix + "pp_degree"] = _ask_field(
535
+ "What is the Pipeline Parallelism degree/size? [1]:",
536
+ int,
537
+ default=1,
538
+ error_message="Please enter an integer.",
539
+ )
540
+ if megatron_lm_config[prefix + "pp_degree"] > 1:
541
+ megatron_lm_config[prefix + "num_micro_batches"] = _ask_field(
542
+ "What is the number of micro-batches? [1]:",
543
+ int,
544
+ default=1,
545
+ error_message="Please enter an integer.",
546
+ )
547
+
548
+ megatron_lm_config[prefix + "recompute_activations"] = _ask_field(
549
+ "Do you want to enable selective activation recomputation? [YES/no]: ",
550
+ _convert_yes_no_to_bool,
551
+ default=True,
552
+ error_message="Please enter yes or no.",
553
+ )
554
+
555
+ megatron_lm_config[prefix + "use_distributed_optimizer"] = _ask_field(
556
+ "Do you want to use distributed optimizer "
557
+ "which shards optimizer state and gradients across data parallel ranks? [YES/no]: ",
558
+ _convert_yes_no_to_bool,
559
+ default=True,
560
+ error_message="Please enter yes or no.",
561
+ )
562
+
563
+ megatron_lm_config[prefix + "gradient_clipping"] = _ask_field(
564
+ "What is the gradient clipping value based on global L2 Norm (0 to disable)? [1.0]: ",
565
+ float,
566
+ default=1.0,
567
+ )
568
+ # TPU specific defaults
569
+ tpu_commands = None
570
+ tpu_command_file = None
571
+ tpu_downcast_bf16 = "no"
572
+ tpu_env = []
573
+ tpu_name = None
574
+ tpu_vm = None
575
+ tpu_zone = None
576
+ tpu_use_sudo = False
577
+ tpu_use_cluster = False
578
+
579
+ if distributed_type in [
580
+ DistributedType.MULTI_CPU,
581
+ DistributedType.MULTI_XPU,
582
+ DistributedType.MULTI_HPU,
583
+ DistributedType.MULTI_GPU,
584
+ DistributedType.MULTI_MLU,
585
+ DistributedType.MULTI_SDAA,
586
+ DistributedType.MULTI_MUSA,
587
+ DistributedType.MULTI_NPU,
588
+ DistributedType.XLA,
589
+ ]:
590
+ machine_type = str(distributed_type).split(".")[1].replace("MULTI_", "")
591
+ if machine_type == "TPU":
592
+ machine_type += " cores"
593
+ elif machine_type == "CPU":
594
+ machine_type = "processes"
595
+ else:
596
+ machine_type += "(s)"
597
+ num_processes = _ask_field(
598
+ f"How many {machine_type} should be used for distributed training? [1]:",
599
+ int,
600
+ default=1,
601
+ error_message="Please enter an integer.",
602
+ )
603
+ elif distributed_type in [DistributedType.FSDP, DistributedType.DEEPSPEED, DistributedType.MEGATRON_LM]:
604
+ num_processes = _ask_field(
605
+ "How many GPU(s) should be used for distributed training? [1]:",
606
+ int,
607
+ default=1,
608
+ error_message="Please enter an integer.",
609
+ )
610
+ else:
611
+ num_processes = 1
612
+
613
+ if (distributed_type == DistributedType.MULTI_GPU) and (num_machines == 1) and (num_processes == 1):
614
+ raise ValueError(
615
+ 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."
616
+ )
617
+
618
+ if (
619
+ distributed_type
620
+ in [
621
+ DistributedType.MULTI_GPU,
622
+ DistributedType.MULTI_MLU,
623
+ DistributedType.MULTI_SDAA,
624
+ DistributedType.MULTI_MUSA,
625
+ DistributedType.MULTI_NPU,
626
+ DistributedType.MULTI_XPU,
627
+ DistributedType.MULTI_HPU,
628
+ DistributedType.NO,
629
+ ]
630
+ and not use_cpu
631
+ and not use_mps
632
+ ):
633
+ if is_npu_available():
634
+ machine_type = "NPU(s)"
635
+ elif is_mlu_available():
636
+ machine_type = "MLU(s)"
637
+ elif is_sdaa_available():
638
+ machine_type = "SDAA(s)"
639
+ elif is_musa_available():
640
+ machine_type = "MUSA(s)"
641
+ elif is_xpu_available():
642
+ machine_type = "XPU(s)"
643
+ elif is_hpu_available():
644
+ machine_type = "HPU(s)"
645
+ else:
646
+ machine_type = "GPU(s)"
647
+ gpu_ids = _ask_field(
648
+ f"What {machine_type} (by id) should be used for training on this machine as a comma-separated list? [all]:",
649
+ default="all",
650
+ )
651
+
652
+ # CPU affinity is only supported on NVIDIA hardware for now
653
+ enable_cpu_affinity = False
654
+ if distributed_type in (DistributedType.NO, DistributedType.MULTI_GPU) and not use_cpu and not use_mps:
655
+ enable_cpu_affinity = _ask_field(
656
+ "Would you like to enable numa efficiency? (Currently only supported on NVIDIA hardware). [yes/NO]: ",
657
+ _convert_yes_no_to_bool,
658
+ default=False,
659
+ error_message="Please enter yes or no.",
660
+ )
661
+
662
+ fp8_config = None
663
+ if distributed_type == DistributedType.XLA:
664
+ mixed_precision = "no"
665
+ main_training_function = _ask_field(
666
+ "What is the name of the function in your script that should be launched in all parallel scripts? [main]: ",
667
+ default="main",
668
+ )
669
+ tpu_use_cluster = _ask_field(
670
+ "Are you using a TPU cluster? [yes/NO]: ",
671
+ _convert_yes_no_to_bool,
672
+ default=False,
673
+ error_message="Please enter yes or no.",
674
+ )
675
+ if tpu_use_cluster:
676
+ tpu_name = _ask_field(
677
+ "What is the name of your TPU cluster? ",
678
+ default=None,
679
+ error_message="Please enter the name of your TPU cluster.",
680
+ )
681
+ tpu_zone = _ask_field(
682
+ "What is the zone of your TPU cluster? ",
683
+ default=None,
684
+ error_message="Please enter the zone of your TPU cluster.",
685
+ )
686
+ tpu_use_sudo = _ask_field(
687
+ "To run a python script in a TPU pod, should `sudo` be used? [yes/NO]: ",
688
+ default=False,
689
+ error_message="Please enter yes or no.",
690
+ )
691
+ run_commands = _ask_field(
692
+ "Do you have code you wish to run on startup in each pod? [yes/NO]: ",
693
+ _convert_yes_no_to_bool,
694
+ default=False,
695
+ error_message="Please enter yes or no.",
696
+ )
697
+ if run_commands:
698
+ use_command_file = _ask_field(
699
+ "Is this code located in a bash script? [yes/NO]: ",
700
+ _convert_yes_no_to_bool,
701
+ default=False,
702
+ error_message="Please enter yes or no.",
703
+ )
704
+ if use_command_file:
705
+ tpu_command_file = _ask_field(
706
+ "What is the path to your bash script? ",
707
+ default=None,
708
+ error_message="Please enter the path to your bash script.",
709
+ )
710
+ tpu_command_file = os.path.abspath(tpu_command_file)
711
+ else:
712
+ print("Please enter each command separately you wish to run on startup in each pod.")
713
+ tpu_commands = []
714
+ another_command = True
715
+ while another_command:
716
+ tpu_commands.append(
717
+ _ask_field(
718
+ "Please enter a single command to be ran ",
719
+ default=None,
720
+ error_message="Please enter the commands you wish to run on startup in each pod as a single string.",
721
+ )
722
+ )
723
+ another_command = _ask_field(
724
+ "Do you wish to add another command? [yes/NO]: ",
725
+ _convert_yes_no_to_bool,
726
+ default=False,
727
+ error_message="Please enter yes or no.",
728
+ )
729
+ tpu_vm = _ask_field(
730
+ "If not using an instance group, what are the names of the Compute VM instances to be used, separated by a comma: ",
731
+ default="",
732
+ ).split(",")
733
+ tpu_env = _ask_field(
734
+ "What environment variables do you wish to set in each pod, separated by a comma: ",
735
+ default="",
736
+ ).split(",")
737
+
738
+ else:
739
+ main_training_function = "main"
740
+ if distributed_type == DistributedType.DEEPSPEED and use_deepspeed_config:
741
+ mixed_precision = None
742
+ else:
743
+ mixed_precision = _ask_options(
744
+ "Do you wish to use mixed precision?",
745
+ ["no", "fp16", "bf16", "fp8"],
746
+ _convert_mixed_precision,
747
+ )
748
+ if mixed_precision == "fp8":
749
+ if not is_fp8_available():
750
+ raise ValueError("FP8 (either Transformer Engine or MSAMP) is not installed on this machine.")
751
+ fp8_config = {}
752
+ fp8_config["backend"] = _ask_options(
753
+ "Which FP8 backend do you want to use?",
754
+ ["te", "msamp"],
755
+ _convert_fp8_backend,
756
+ )
757
+ if fp8_config["backend"] == "TE":
758
+ if not is_transformer_engine_available():
759
+ raise ValueError("TransformersEngine was selected, but it is not installed on this machine.")
760
+ fp8_config["use_autocast_during_eval"] = _ask_field(
761
+ "Do you want to use FP8 autocast during eval mode? Generally better metrics are found when this is disabled [yes/NO]: ",
762
+ _convert_yes_no_to_bool,
763
+ default=False,
764
+ )
765
+ fp8_config["margin"] = _ask_field(
766
+ "What margin should be used for gradient scaling? [0]: ",
767
+ int,
768
+ default=0,
769
+ )
770
+ fp8_config["interval"] = _ask_field(
771
+ "What interval should be used for for how often the scaling factor is recomputed? [1]: ",
772
+ int,
773
+ default=1,
774
+ )
775
+ fp8_config["fp8_format"] = _ask_options(
776
+ "Which weight format should be used?",
777
+ ["HYBRID", "E4M3", "E5M2"],
778
+ lambda i: ["HYBRID", "E4M3", "E5M2"][i],
779
+ default=0,
780
+ )
781
+ fp8_config["amax_history_length"] = _ask_field(
782
+ "What length of history should be used for the amax scaling factor computation? [1024]: ",
783
+ int,
784
+ default=1024,
785
+ )
786
+ fp8_config["amax_compute_algorithm"] = _ask_options(
787
+ "Which algorithm should be used for the amax scaling factor computation?",
788
+ ["max", "most_recent"],
789
+ lambda x: "max" if x == 0 else "most_recent",
790
+ default=0,
791
+ )
792
+ fp8_config["override_linear_precision"] = _ask_field(
793
+ "Do you want to to execute `fprop`, `dgrad`, and `wgrad` GEMMS in higher precision? [yes/NO]: ",
794
+ _convert_yes_no_to_bool,
795
+ default=False,
796
+ )
797
+ if fp8_config["override_linear_precision"]:
798
+ fprop = _ask_field(
799
+ "Should `fprop` be executed in higher precision? [yes/NO]: ",
800
+ _convert_yes_no_to_bool,
801
+ default=False,
802
+ )
803
+ dgrad = _ask_field(
804
+ "Should `dgrad` be executed in higher precision? [yes/NO]: ",
805
+ _convert_yes_no_to_bool,
806
+ default=False,
807
+ )
808
+ wgrad = _ask_field(
809
+ "Should `wgrad` be executed in higher precision? [yes/NO]: ",
810
+ _convert_yes_no_to_bool,
811
+ default=False,
812
+ )
813
+ fp8_config["override_linear_precision"] = (fprop, dgrad, wgrad)
814
+ else:
815
+ fp8_config["override_linear_precision"] = (False, False, False)
816
+
817
+ elif fp8_config["backend"] == "MSAMP":
818
+ if not is_msamp_available():
819
+ raise ValueError("MSAMP was selected, but it is not installed on this machine.")
820
+ fp8_config["optimization_level"] = _ask_options(
821
+ "Which optimization level should be used?",
822
+ ["O1", "O2"],
823
+ lambda x: "O1" if x == 0 else "O2",
824
+ default=1,
825
+ )
826
+
827
+ if use_dynamo and mixed_precision == "no" and not use_cpu:
828
+ print(
829
+ "Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts."
830
+ )
831
+
832
+ if distributed_type == DistributedType.XLA and mixed_precision == "bf16":
833
+ tpu_downcast_bf16 = _ask_field(
834
+ "Should `torch.float` be cast as `bfloat16` and `torch.double` remain `float32` on TPUs?", default="no"
835
+ )
836
+
837
+ return ClusterConfig(
838
+ compute_environment=ComputeEnvironment.LOCAL_MACHINE,
839
+ distributed_type=distributed_type,
840
+ num_processes=num_processes,
841
+ gpu_ids=gpu_ids,
842
+ mixed_precision=mixed_precision,
843
+ downcast_bf16=tpu_downcast_bf16,
844
+ machine_rank=machine_rank,
845
+ num_machines=num_machines,
846
+ main_process_ip=main_process_ip,
847
+ main_process_port=main_process_port,
848
+ main_training_function=main_training_function,
849
+ fp8_config=fp8_config,
850
+ deepspeed_config=deepspeed_config,
851
+ fsdp_config=fsdp_config,
852
+ megatron_lm_config=megatron_lm_config,
853
+ ipex_config=ipex_config,
854
+ mpirun_config=mpirun_config,
855
+ use_cpu=use_cpu,
856
+ rdzv_backend=rdzv_backend,
857
+ same_network=same_network,
858
+ commands=tpu_commands,
859
+ command_file=tpu_command_file,
860
+ tpu_env=tpu_env,
861
+ tpu_name=tpu_name,
862
+ tpu_vm=tpu_vm,
863
+ tpu_zone=tpu_zone,
864
+ tpu_use_sudo=tpu_use_sudo,
865
+ tpu_use_cluster=tpu_use_cluster,
866
+ dynamo_config=dynamo_config,
867
+ debug=debug,
868
+ enable_cpu_affinity=enable_cpu_affinity,
869
+ )
venv/lib/python3.10/site-packages/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()
venv/lib/python3.10/site-packages/accelerate/commands/config/config_args.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 megatron_lm
198
+ megatron_lm_config: dict = None
199
+ # args for ipex
200
+ ipex_config: dict = None
201
+ # args for mpirun
202
+ mpirun_config: dict = None
203
+ # args for TPU
204
+ downcast_bf16: bool = False
205
+
206
+ # args for TPU pods
207
+ tpu_name: str = None
208
+ tpu_zone: str = None
209
+ tpu_use_cluster: bool = False
210
+ tpu_use_sudo: bool = False
211
+ command_file: str = None
212
+ commands: list[str] = None
213
+ tpu_vm: list[str] = None
214
+ tpu_env: list[str] = None
215
+
216
+ # args for dynamo
217
+ dynamo_config: dict = None
218
+
219
+ def __post_init__(self):
220
+ if self.deepspeed_config is None:
221
+ self.deepspeed_config = {}
222
+ if self.fsdp_config is None:
223
+ self.fsdp_config = {}
224
+ if self.megatron_lm_config is None:
225
+ self.megatron_lm_config = {}
226
+ if self.ipex_config is None:
227
+ self.ipex_config = {}
228
+ if self.mpirun_config is None:
229
+ self.mpirun_config = {}
230
+ if self.fp8_config is None:
231
+ self.fp8_config = {}
232
+ return super().__post_init__()
233
+
234
+
235
+ @dataclass
236
+ class SageMakerConfig(BaseConfig):
237
+ ec2_instance_type: str
238
+ iam_role_name: str
239
+ image_uri: Optional[str] = None
240
+ profile: Optional[str] = None
241
+ region: str = "us-east-1"
242
+ num_machines: int = 1
243
+ gpu_ids: str = "all"
244
+ base_job_name: str = f"accelerate-sagemaker-{num_machines}"
245
+ pytorch_version: str = SAGEMAKER_PYTORCH_VERSION
246
+ transformers_version: str = SAGEMAKER_TRANSFORMERS_VERSION
247
+ py_version: str = SAGEMAKER_PYTHON_VERSION
248
+ sagemaker_inputs_file: str = None
249
+ sagemaker_metrics_file: str = None
250
+ additional_args: dict = None
251
+ dynamo_config: dict = None
252
+ enable_cpu_affinity: bool = False
venv/lib/python3.10/site-packages/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
venv/lib/python3.10/site-packages/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}")
venv/lib/python3.10/site-packages/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
+ )
venv/lib/python3.10/site-packages/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}.")
venv/lib/python3.10/site-packages/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())
venv/lib/python3.10/site-packages/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()
venv/lib/python3.10/site-packages/accelerate/commands/launch.py ADDED
@@ -0,0 +1,1209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_megatron_lm",
274
+ default=False,
275
+ action="store_true",
276
+ help="Whether to use Megatron-LM.",
277
+ )
278
+
279
+ paradigm_args.add_argument(
280
+ "--use_xpu",
281
+ default=None,
282
+ action="store_true",
283
+ 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.",
284
+ )
285
+
286
+ # distributed GPU training arguments
287
+ distributed_args = parser.add_argument_group("Distributed GPUs", "Arguments related to distributed GPU training.")
288
+ distributed_args.add_argument(
289
+ "--gpu_ids",
290
+ default=None,
291
+ help="What GPUs (by id) should be used for training on this machine as a comma-separated list",
292
+ )
293
+ distributed_args.add_argument(
294
+ "--same_network",
295
+ default=False,
296
+ action="store_true",
297
+ help="Whether all machines used for multinode training exist on the same local network.",
298
+ )
299
+ distributed_args.add_argument(
300
+ "--machine_rank", type=int, default=None, help="The rank of the machine on which this script is launched."
301
+ )
302
+ distributed_args.add_argument(
303
+ "--main_process_ip", type=str, default=None, help="The IP address of the machine of rank 0."
304
+ )
305
+ distributed_args.add_argument(
306
+ "--main_process_port",
307
+ type=int,
308
+ default=None,
309
+ help="The port to use to communicate with the machine of rank 0.",
310
+ )
311
+ distributed_args.add_argument(
312
+ "-t",
313
+ "--tee",
314
+ default="0",
315
+ type=str,
316
+ help="Tee std streams into a log file and also to console.",
317
+ )
318
+ distributed_args.add_argument(
319
+ "--log_dir",
320
+ type=str,
321
+ default=None,
322
+ help=(
323
+ "Base directory to use for log files when using torchrun/torch.distributed.run as launcher. "
324
+ "Use with --tee to redirect std streams info log files."
325
+ ),
326
+ )
327
+ distributed_args.add_argument(
328
+ "--role",
329
+ type=str,
330
+ default="default",
331
+ help="User-defined role for the workers.",
332
+ )
333
+ # Rendezvous related arguments
334
+ distributed_args.add_argument(
335
+ "--rdzv_backend",
336
+ type=str,
337
+ default="static",
338
+ help="The rendezvous method to use, such as 'static' (the default) or 'c10d'",
339
+ )
340
+ distributed_args.add_argument(
341
+ "--rdzv_conf",
342
+ type=str,
343
+ default="",
344
+ help="Additional rendezvous configuration (<key1>=<value1>,<key2>=<value2>,...).",
345
+ )
346
+ distributed_args.add_argument(
347
+ "--max_restarts",
348
+ type=int,
349
+ default=0,
350
+ help="Maximum number of worker group restarts before failing.",
351
+ )
352
+ distributed_args.add_argument(
353
+ "--monitor_interval",
354
+ type=float,
355
+ default=0.1,
356
+ help="Interval, in seconds, to monitor the state of workers.",
357
+ )
358
+ parser.add_argument(
359
+ "-m",
360
+ "--module",
361
+ action="store_true",
362
+ help="Change each process to interpret the launch script as a Python module, executing with the same behavior as 'python -m'.",
363
+ )
364
+ parser.add_argument(
365
+ "--no_python",
366
+ action="store_true",
367
+ help="Skip prepending the training script with 'python' - just execute it directly. Useful when the script is not a Python script.",
368
+ )
369
+
370
+ # TPU arguments
371
+ tpu_args = parser.add_argument_group("TPU", "Arguments related to TPU.")
372
+ tpu_args.add_argument(
373
+ "--tpu_cluster",
374
+ action="store_true",
375
+ dest="tpu_use_cluster",
376
+ help="Whether to use a GCP TPU pod for training.",
377
+ )
378
+ tpu_args.add_argument(
379
+ "--no_tpu_cluster",
380
+ action="store_false",
381
+ dest="tpu_use_cluster",
382
+ help="Should not be passed explicitly, this is for internal use only.",
383
+ )
384
+ tpu_args.add_argument(
385
+ "--tpu_use_sudo",
386
+ action="store_true",
387
+ help="Whether to use `sudo` when running the TPU training script in each pod.",
388
+ )
389
+ tpu_args.add_argument(
390
+ "--vm",
391
+ type=str,
392
+ action="append",
393
+ help=(
394
+ "List of single Compute VM instance names. "
395
+ "If not provided we assume usage of instance groups. For TPU pods."
396
+ ),
397
+ )
398
+ tpu_args.add_argument(
399
+ "--env",
400
+ type=str,
401
+ action="append",
402
+ help="List of environment variables to set on the Compute VM instances. For TPU pods.",
403
+ )
404
+ tpu_args.add_argument(
405
+ "--main_training_function",
406
+ type=str,
407
+ default=None,
408
+ help="The name of the main function to be executed in your script (only for TPU training).",
409
+ )
410
+ tpu_args.add_argument(
411
+ "--downcast_bf16",
412
+ action="store_true",
413
+ 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.",
414
+ )
415
+
416
+ # DeepSpeed arguments
417
+ deepspeed_args = parser.add_argument_group("DeepSpeed Arguments", "Arguments related to DeepSpeed.")
418
+ deepspeed_args.add_argument(
419
+ "--deepspeed_config_file",
420
+ default=None,
421
+ type=str,
422
+ help="DeepSpeed config file.",
423
+ )
424
+ deepspeed_args.add_argument(
425
+ "--zero_stage",
426
+ default=None,
427
+ type=int,
428
+ help="DeepSpeed's ZeRO optimization stage (useful only when `use_deepspeed` flag is passed). "
429
+ "If unspecified, will default to `2`.",
430
+ )
431
+ deepspeed_args.add_argument(
432
+ "--offload_optimizer_device",
433
+ default=None,
434
+ type=str,
435
+ help="Decides where (none|cpu|nvme) to offload optimizer states (useful only when `use_deepspeed` flag is passed). "
436
+ "If unspecified, will default to 'none'.",
437
+ )
438
+ deepspeed_args.add_argument(
439
+ "--offload_param_device",
440
+ default=None,
441
+ type=str,
442
+ help="Decides where (none|cpu|nvme) to offload parameters (useful only when `use_deepspeed` flag is passed). "
443
+ "If unspecified, will default to 'none'.",
444
+ )
445
+ deepspeed_args.add_argument(
446
+ "--offload_optimizer_nvme_path",
447
+ default=None,
448
+ type=str,
449
+ help="Decides Nvme Path to offload optimizer states (useful only when `use_deepspeed` flag is passed). "
450
+ "If unspecified, will default to 'none'.",
451
+ )
452
+ deepspeed_args.add_argument(
453
+ "--offload_param_nvme_path",
454
+ default=None,
455
+ type=str,
456
+ help="Decides Nvme Path to offload parameters (useful only when `use_deepspeed` flag is passed). "
457
+ "If unspecified, will default to 'none'.",
458
+ )
459
+ deepspeed_args.add_argument(
460
+ "--gradient_accumulation_steps",
461
+ default=None,
462
+ type=int,
463
+ help="No of gradient_accumulation_steps used in your training script (useful only when `use_deepspeed` flag is passed). "
464
+ "If unspecified, will default to `1`.",
465
+ )
466
+ deepspeed_args.add_argument(
467
+ "--gradient_clipping",
468
+ default=None,
469
+ type=float,
470
+ help="gradient clipping value used in your training script (useful only when `use_deepspeed` flag is passed). "
471
+ "If unspecified, will default to `1.0`.",
472
+ )
473
+ deepspeed_args.add_argument(
474
+ "--zero3_init_flag",
475
+ default=None,
476
+ type=str,
477
+ help="Decides Whether (true|false) to enable `deepspeed.zero.Init` for constructing massive models. "
478
+ "Only applicable with DeepSpeed ZeRO Stage-3. If unspecified, will default to `true`.",
479
+ )
480
+ deepspeed_args.add_argument(
481
+ "--zero3_save_16bit_model",
482
+ default=None,
483
+ type=str,
484
+ help="Decides Whether (true|false) to save 16-bit model weights when using ZeRO Stage-3. "
485
+ "Only applicable with DeepSpeed ZeRO Stage-3. If unspecified, will default to `false`.",
486
+ )
487
+ deepspeed_args.add_argument(
488
+ "--deepspeed_hostfile",
489
+ default=None,
490
+ type=str,
491
+ help="DeepSpeed hostfile for configuring multi-node compute resources.",
492
+ )
493
+ deepspeed_args.add_argument(
494
+ "--deepspeed_exclusion_filter",
495
+ default=None,
496
+ type=str,
497
+ help="DeepSpeed exclusion filter string when using mutli-node setup.",
498
+ )
499
+ deepspeed_args.add_argument(
500
+ "--deepspeed_inclusion_filter",
501
+ default=None,
502
+ type=str,
503
+ help="DeepSpeed inclusion filter string when using mutli-node setup.",
504
+ )
505
+ deepspeed_args.add_argument(
506
+ "--deepspeed_multinode_launcher",
507
+ default=None,
508
+ type=str,
509
+ 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`.",
510
+ )
511
+ deepspeed_args.add_argument(
512
+ "--deepspeed_moe_layer_cls_names",
513
+ default=None,
514
+ type=str,
515
+ help="comma-separated list of transformer MoE layer class names (case-sensitive) to wrap ,e.g, `MixtralSparseMoeBlock`, `Qwen2MoeSparseMoeBlock`, `JetMoEAttention,JetMoEBlock` ..."
516
+ " (useful only when `use_deepspeed` flag is passed).",
517
+ )
518
+
519
+ # fsdp arguments
520
+ fsdp_args = parser.add_argument_group("FSDP Arguments", "Arguments related to Fully Shared Data Parallelism.")
521
+ fsdp_args.add_argument(
522
+ "--fsdp_version",
523
+ type=str,
524
+ default="1",
525
+ choices=["1", "2"],
526
+ help="FSDP version to use. (useful only when `use_fsdp` flag is passed).",
527
+ )
528
+ fsdp_args.add_argument(
529
+ "--fsdp_offload_params",
530
+ default="false",
531
+ type=str,
532
+ help="Decides Whether (true|false) to offload parameters and gradients to CPU. (useful only when `use_fsdp` flag is passed).",
533
+ )
534
+ fsdp_args.add_argument(
535
+ "--fsdp_min_num_params",
536
+ type=int,
537
+ default=1e8,
538
+ help="FSDP's minimum number of parameters for Default Auto Wrapping. (useful only when `use_fsdp` flag is passed).",
539
+ )
540
+ # We enable this for backwards compatibility, throw a warning if this is set in `FullyShardedDataParallelPlugin`
541
+ fsdp_args.add_argument(
542
+ "--fsdp_sharding_strategy",
543
+ type=str,
544
+ default="FULL_SHARD",
545
+ help="FSDP's sharding strategy. (useful only when `use_fsdp` flag is passed and `fsdp_version=1`).",
546
+ )
547
+ fsdp_args.add_argument(
548
+ "--fsdp_reshard_after_forward",
549
+ type=str,
550
+ default="true",
551
+ 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).",
552
+ )
553
+ fsdp_args.add_argument(
554
+ "--fsdp_auto_wrap_policy",
555
+ type=str,
556
+ default=None,
557
+ help="FSDP's auto wrap policy. (useful only when `use_fsdp` flag is passed).",
558
+ )
559
+ fsdp_args.add_argument(
560
+ "--fsdp_transformer_layer_cls_to_wrap",
561
+ default=None,
562
+ type=str,
563
+ help="Transformer layer class name (case-sensitive) to wrap ,e.g, `BertLayer`, `GPTJBlock`, `T5Block` .... "
564
+ "(useful only when `use_fsdp` flag is passed).",
565
+ )
566
+ fsdp_args.add_argument(
567
+ "--fsdp_backward_prefetch",
568
+ default=None,
569
+ type=str,
570
+ help="FSDP's backward prefetch policy. (useful only when `use_fsdp` flag is passed).",
571
+ )
572
+ fsdp_args.add_argument(
573
+ "--fsdp_state_dict_type",
574
+ default=None,
575
+ type=str,
576
+ help="FSDP's state dict type. (useful only when `use_fsdp` flag is passed).",
577
+ )
578
+ fsdp_args.add_argument(
579
+ "--fsdp_forward_prefetch",
580
+ default="false",
581
+ type=str,
582
+ help="If True, then FSDP explicitly prefetches the next upcoming "
583
+ "all-gather while executing in the forward pass (useful only when `use_fsdp` flag is passed).",
584
+ )
585
+ fsdp_args.add_argument(
586
+ "--fsdp_use_orig_params",
587
+ default="true",
588
+ type=str,
589
+ help="If True, allows non-uniform `requires_grad` during init, which means support for interspersed frozen and trainable paramteres."
590
+ " (useful only when `use_fsdp` flag is passed).",
591
+ )
592
+ fsdp_args.add_argument(
593
+ "--fsdp_cpu_ram_efficient_loading",
594
+ default="true",
595
+ type=str,
596
+ help="If True, only the first process loads the pretrained model checkoint while all other processes have empty weights. "
597
+ "Only applicable for 🤗 Transformers. When using this, `--fsdp_sync_module_states` needs to True. "
598
+ "(useful only when `use_fsdp` flag is passed).",
599
+ )
600
+ fsdp_args.add_argument(
601
+ "--fsdp_sync_module_states",
602
+ default="true",
603
+ type=str,
604
+ help="If True, each individually wrapped FSDP unit will broadcast module parameters from rank 0."
605
+ " (useful only when `use_fsdp` flag is passed).",
606
+ )
607
+ fsdp_args.add_argument(
608
+ "--fsdp_activation_checkpointing",
609
+ default="false",
610
+ type=str,
611
+ 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).",
612
+ )
613
+
614
+ # megatron_lm args
615
+ megatron_lm_args = parser.add_argument_group("Megatron-LM Arguments", "Arguments related to Megatron-LM.")
616
+ megatron_lm_args.add_argument(
617
+ "--megatron_lm_tp_degree",
618
+ type=int,
619
+ default=1,
620
+ help="Megatron-LM's Tensor Parallelism (TP) degree. (useful only when `use_megatron_lm` flag is passed).",
621
+ )
622
+ megatron_lm_args.add_argument(
623
+ "--megatron_lm_pp_degree",
624
+ type=int,
625
+ default=1,
626
+ help="Megatron-LM's Pipeline Parallelism (PP) degree. (useful only when `use_megatron_lm` flag is passed).",
627
+ )
628
+ megatron_lm_args.add_argument(
629
+ "--megatron_lm_num_micro_batches",
630
+ type=int,
631
+ default=None,
632
+ help="Megatron-LM's number of micro batches when PP degree > 1. (useful only when `use_megatron_lm` flag is passed).",
633
+ )
634
+ megatron_lm_args.add_argument(
635
+ "--megatron_lm_sequence_parallelism",
636
+ default=None,
637
+ type=str,
638
+ help="Decides Whether (true|false) to enable Sequence Parallelism when TP degree > 1. "
639
+ "(useful only when `use_megatron_lm` flag is passed).",
640
+ )
641
+ megatron_lm_args.add_argument(
642
+ "--megatron_lm_recompute_activations",
643
+ default=None,
644
+ type=str,
645
+ help="Decides Whether (true|false) to enable Selective Activation Recomputation. "
646
+ "(useful only when `use_megatron_lm` flag is passed).",
647
+ )
648
+ megatron_lm_args.add_argument(
649
+ "--megatron_lm_use_distributed_optimizer",
650
+ default=None,
651
+ type=str,
652
+ help="Decides Whether (true|false) to use distributed optimizer "
653
+ "which shards optimizer state and gradients across Data Pralellel (DP) ranks. "
654
+ "(useful only when `use_megatron_lm` flag is passed).",
655
+ )
656
+ megatron_lm_args.add_argument(
657
+ "--megatron_lm_gradient_clipping",
658
+ default=1.0,
659
+ type=float,
660
+ help="Megatron-LM's gradient clipping value based on global L2 Norm (0 to disable). "
661
+ "(useful only when `use_megatron_lm` flag is passed).",
662
+ )
663
+
664
+ # FP8 arguments
665
+ fp8_args = parser.add_argument_group(
666
+ "FP8 Arguments", "Arguments related to FP8 training (requires `--mixed_precision=fp8`)"
667
+ )
668
+ fp8_args.add_argument(
669
+ "--fp8_backend",
670
+ type=str,
671
+ choices=["te", "msamp"],
672
+ help="Choose a backend to train with FP8 (te: TransformerEngine, msamp: MS-AMP)",
673
+ )
674
+ fp8_args.add_argument(
675
+ "--fp8_use_autocast_during_eval",
676
+ default=False,
677
+ action="store_true",
678
+ 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.",
679
+ )
680
+ fp8_args.add_argument(
681
+ "--fp8_margin",
682
+ type=int,
683
+ default=0,
684
+ help="The margin to use for the gradient scaling (useful only when `--fp8_backend=te` is passed).",
685
+ )
686
+ fp8_args.add_argument(
687
+ "--fp8_interval",
688
+ type=int,
689
+ default=1,
690
+ help="The interval to use for how often the scaling factor is recomputed (useful only when `--fp8_backend=te` is passed).",
691
+ )
692
+ fp8_args.add_argument(
693
+ "--fp8_format",
694
+ type=str,
695
+ default="HYBRID",
696
+ choices=["HYBRID", "E4M3", "E5M2"],
697
+ help="The format to use for the FP8 recipe (useful only when `--fp8_backend=te` is passed).",
698
+ )
699
+ fp8_args.add_argument(
700
+ "--fp8_amax_history_len",
701
+ type=int,
702
+ default=1024,
703
+ help="The length of the history to use for the scaling factor computation (useful only when `--fp8_backend=te` is passed).",
704
+ )
705
+ fp8_args.add_argument(
706
+ "--fp8_amax_compute_algo",
707
+ type=str,
708
+ default="most_recent",
709
+ choices=["max", "most_recent"],
710
+ help="The algorithm to use for the scaling factor computation. (useful only when `--fp8_backend=te` is passed).",
711
+ )
712
+ fp8_args.add_argument(
713
+ "--fp8_override_linear_precision",
714
+ type=lambda x: tuple(map(str_to_bool, x.split(","))),
715
+ default=(False, False, False),
716
+ 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).",
717
+ )
718
+ fp8_args.add_argument(
719
+ "--fp8_opt_level",
720
+ type=str,
721
+ default="O2",
722
+ choices=["O1", "O2"],
723
+ help="What level of 8-bit collective communication should be used with MS-AMP (useful only when `--fp8_backend=msamp` is passed).",
724
+ )
725
+
726
+ # AWS arguments
727
+ aws_args = parser.add_argument_group("AWS Arguments", "Arguments related to AWS.")
728
+ aws_args.add_argument(
729
+ "--aws_access_key_id",
730
+ type=str,
731
+ default=None,
732
+ help="The AWS_ACCESS_KEY_ID used to launch the Amazon SageMaker training job",
733
+ )
734
+ aws_args.add_argument(
735
+ "--aws_secret_access_key",
736
+ type=str,
737
+ default=None,
738
+ help="The AWS_SECRET_ACCESS_KEY used to launch the Amazon SageMaker training job.",
739
+ )
740
+ parser.add_argument(
741
+ "--debug",
742
+ action="store_true",
743
+ help="Whether to print out the torch.distributed stack trace when something fails.",
744
+ )
745
+ parser.add_argument(
746
+ "training_script",
747
+ type=str,
748
+ help=(
749
+ "The full path to the script to be launched in parallel, followed by all the arguments for the training "
750
+ "script."
751
+ ),
752
+ )
753
+
754
+ # MPI arguments
755
+ mpirun_args = parser.add_argument_group("MPI Arguments", "Arguments related to mpirun for Multi-CPU")
756
+ mpirun_args.add_argument(
757
+ "--mpirun_hostfile",
758
+ type=str,
759
+ default=None,
760
+ help="Location for a hostfile for using Accelerate to launch a multi-CPU training job with mpirun. This will "
761
+ "get passed to the MPI --hostfile or -f parameter, depending on which MPI program is installed.",
762
+ )
763
+ mpirun_args.add_argument(
764
+ "--mpirun_ccl",
765
+ type=int,
766
+ default=1,
767
+ help="The number of oneCCL worker threads when using Accelerate to launch multi-CPU training with mpirun.",
768
+ )
769
+
770
+ # Other arguments of the training scripts
771
+ parser.add_argument("training_script_args", nargs=argparse.REMAINDER, help="Arguments of the training script.")
772
+
773
+ if subparsers is not None:
774
+ parser.set_defaults(func=launch_command)
775
+ return parser
776
+
777
+
778
+ def simple_launcher(args):
779
+ cmd, current_env = prepare_simple_launcher_cmd_env(args)
780
+
781
+ process = subprocess.Popen(cmd, env=current_env)
782
+ process.wait()
783
+ if process.returncode != 0:
784
+ if not args.quiet:
785
+ raise subprocess.CalledProcessError(returncode=process.returncode, cmd=cmd)
786
+ else:
787
+ sys.exit(1)
788
+
789
+
790
+ def multi_gpu_launcher(args):
791
+ import torch.distributed.run as distrib_run
792
+
793
+ current_env = prepare_multi_gpu_env(args)
794
+ if not check_cuda_p2p_ib_support():
795
+ message = "Using RTX 4000 series which doesn't support faster communication speedups. Ensuring P2P and IB communications are disabled."
796
+ warn = False
797
+ if "NCCL_P2P_DISABLE" not in current_env:
798
+ current_env["NCCL_P2P_DISABLE"] = "1"
799
+ warn = True
800
+ if "NCCL_IB_DISABLE" not in current_env:
801
+ current_env["NCCL_IB_DISABLE"] = "1"
802
+ warn = True
803
+ if warn:
804
+ logger.warning(message)
805
+
806
+ debug = getattr(args, "debug", False)
807
+ args = _filter_args(
808
+ args,
809
+ distrib_run.get_args_parser(),
810
+ ["--training_script", args.training_script, "--training_script_args", args.training_script_args],
811
+ )
812
+
813
+ with patch_environment(**current_env):
814
+ try:
815
+ distrib_run.run(args)
816
+ except Exception:
817
+ if is_rich_available() and debug:
818
+ console = get_console()
819
+ console.print("\n[bold red]Using --debug, `torch.distributed` Stack Trace:[/bold red]")
820
+ console.print_exception(suppress=[__file__], show_locals=False)
821
+ else:
822
+ raise
823
+
824
+
825
+ def deepspeed_launcher(args):
826
+ import torch.distributed.run as distrib_run
827
+
828
+ if not is_deepspeed_available():
829
+ raise ImportError("DeepSpeed is not installed => run `pip3 install deepspeed` or build it from source.")
830
+ else:
831
+ from deepspeed.launcher.runner import DEEPSPEED_ENVIRONMENT_NAME
832
+
833
+ cmd, current_env = prepare_deepspeed_cmd_env(args)
834
+ if not check_cuda_p2p_ib_support():
835
+ message = "Using RTX 4000 series which doesn't support faster communication speedups. Ensuring P2P and IB communications are disabled."
836
+ warn = False
837
+ if "NCCL_P2P_DISABLE" not in current_env:
838
+ current_env["NCCL_P2P_DISABLE"] = "1"
839
+ warn = True
840
+ if "NCCL_IB_DISABLE" not in current_env:
841
+ current_env["NCCL_IB_DISABLE"] = "1"
842
+ warn = True
843
+ if warn:
844
+ logger.warning(message)
845
+
846
+ if args.num_machines > 1 and args.deepspeed_multinode_launcher != DEEPSPEED_MULTINODE_LAUNCHERS[1]:
847
+ with open(DEEPSPEED_ENVIRONMENT_NAME, "a") as f:
848
+ valid_env_items = convert_dict_to_env_variables(current_env)
849
+ if len(valid_env_items) > 1:
850
+ f.writelines(valid_env_items)
851
+
852
+ process = subprocess.Popen(cmd, env=current_env)
853
+ process.wait()
854
+ if process.returncode != 0:
855
+ if not args.quiet:
856
+ raise subprocess.CalledProcessError(returncode=process.returncode, cmd=cmd)
857
+ else:
858
+ sys.exit(1)
859
+ else:
860
+ debug = getattr(args, "debug", False)
861
+ args = _filter_args(
862
+ args,
863
+ distrib_run.get_args_parser(),
864
+ ["--training_script", args.training_script, "--training_script_args", args.training_script_args],
865
+ )
866
+ with patch_environment(**current_env):
867
+ try:
868
+ distrib_run.run(args)
869
+ except Exception:
870
+ if is_rich_available() and debug:
871
+ console = get_console()
872
+ console.print("\n[bold red]Using --debug, `torch.distributed` Stack Trace:[/bold red]")
873
+ console.print_exception(suppress=[__file__], show_locals=False)
874
+ else:
875
+ raise
876
+
877
+
878
+ def tpu_launcher(args):
879
+ import torch_xla.distributed.xla_multiprocessing as xmp
880
+
881
+ if args.no_python:
882
+ raise ValueError("--no_python cannot be used with TPU launcher")
883
+
884
+ args, current_env = prepare_tpu(args, {})
885
+
886
+ if args.module:
887
+ mod_name = args.training_script
888
+ else:
889
+ # Import training_script as a module
890
+ script_path = Path(args.training_script)
891
+ sys.path.append(str(script_path.parent.resolve()))
892
+ mod_name = script_path.stem
893
+
894
+ mod = importlib.import_module(mod_name)
895
+ if not hasattr(mod, args.main_training_function):
896
+ raise ValueError(
897
+ f"Your training script should have a function named {args.main_training_function}, or you should pass a "
898
+ "different value to `--main_training_function`."
899
+ )
900
+
901
+ # Patch sys.argv
902
+ sys.argv = [mod.__file__] + args.training_script_args
903
+
904
+ main_function = getattr(mod, args.main_training_function)
905
+ with patch_environment(**current_env):
906
+ xmp.spawn(PrepareForLaunch(main_function), args=())
907
+
908
+
909
+ def tpu_pod_launcher(args):
910
+ from torch_xla.distributed import xla_dist
911
+
912
+ current_env = {}
913
+ args, current_env = prepare_tpu(args, current_env, True)
914
+ debug = getattr(args, "debug", False)
915
+
916
+ training_script = args.training_script
917
+ training_script_args = args.training_script_args
918
+ new_args = _filter_args(
919
+ args, xla_dist.get_args_parser(), ["--tpu", args.tpu_name, "--positional", "", "--restart-tpuvm-pod-server"]
920
+ )
921
+
922
+ if args.tpu_use_sudo:
923
+ new_cmd = ["sudo"]
924
+ else:
925
+ new_cmd = []
926
+
927
+ new_cmd += [
928
+ "accelerate-launch",
929
+ "--tpu",
930
+ "--no_tpu_cluster",
931
+ "--num_machines",
932
+ "1",
933
+ "--mixed_precision",
934
+ "no",
935
+ "--dynamo_backend",
936
+ "no",
937
+ "--num_processes",
938
+ str(args.num_processes),
939
+ "--main_training_function",
940
+ str(args.main_training_function),
941
+ training_script,
942
+ ] + training_script_args
943
+
944
+ new_args.positional = new_cmd
945
+ bad_flags = ""
946
+ for arg in vars(new_args):
947
+ if arg.startswith("docker_"):
948
+ value = getattr(new_args, arg)
949
+ if value != "" and value is not None:
950
+ bad_flags += f'{arg}="{value}"\n'
951
+ if bad_flags != "":
952
+ raise ValueError(
953
+ f"Docker containers are not supported for TPU pod launcher currently, please remove the following flags:\n{bad_flags}"
954
+ )
955
+ new_args.env = [f"{k}={v}" for k, v in current_env.items()]
956
+ new_args.env.append("ACCELERATE_IN_TPU_POD=1")
957
+ try:
958
+ xla_dist.resolve_and_execute(new_args)
959
+ except Exception:
960
+ if is_rich_available() and debug:
961
+ console = get_console()
962
+ console.print("\n[bold red]Using --debug, `torch_xla.xla_dist` Stack Trace:[/bold red]")
963
+ console.print_exception(suppress=[__file__], show_locals=False)
964
+ else:
965
+ raise
966
+
967
+
968
+ def sagemaker_launcher(sagemaker_config: SageMakerConfig, args):
969
+ if not is_sagemaker_available():
970
+ raise ImportError(
971
+ "Please install sagemaker to be able to launch training on Amazon SageMaker with `pip install accelerate[sagemaker]`"
972
+ )
973
+ if args.module or args.no_python:
974
+ raise ValueError(
975
+ "SageMaker requires a python training script file and cannot be used with --module or --no_python"
976
+ )
977
+
978
+ from sagemaker.huggingface import HuggingFace
979
+
980
+ args, sagemaker_inputs = prepare_sagemager_args_inputs(sagemaker_config, args)
981
+
982
+ huggingface_estimator = HuggingFace(**args)
983
+
984
+ huggingface_estimator.fit(inputs=sagemaker_inputs)
985
+ print(f"You can find your model data at: {huggingface_estimator.model_data}")
986
+
987
+
988
+ def _validate_launch_command(args):
989
+ # Sanity checks
990
+ if sum([args.multi_gpu, args.cpu, args.tpu, args.use_deepspeed, args.use_fsdp]) > 1:
991
+ raise ValueError(
992
+ "You can only use one of `--cpu`, `--multi_gpu`, `--tpu`, `--use_deepspeed`, `--use_fsdp` at a time."
993
+ )
994
+ if args.multi_gpu and (args.num_processes is not None) and (args.num_processes < 2):
995
+ raise ValueError("You need to use at least 2 processes to use `--multi_gpu`.")
996
+
997
+ defaults = None
998
+ warned = []
999
+ mp_from_config_flag = False
1000
+ # Get the default from the config file.
1001
+ if args.config_file is not None or os.path.isfile(default_config_file) and not args.cpu:
1002
+ defaults = load_config_from_file(args.config_file)
1003
+ if (
1004
+ not args.multi_gpu
1005
+ and not args.tpu
1006
+ and not args.tpu_use_cluster
1007
+ and not args.use_deepspeed
1008
+ and not args.use_fsdp
1009
+ and not args.use_megatron_lm
1010
+ ):
1011
+ args.use_deepspeed = defaults.distributed_type == DistributedType.DEEPSPEED
1012
+ args.multi_gpu = (
1013
+ True
1014
+ if defaults.distributed_type
1015
+ in (
1016
+ DistributedType.MULTI_GPU,
1017
+ DistributedType.MULTI_NPU,
1018
+ DistributedType.MULTI_MLU,
1019
+ DistributedType.MULTI_SDAA,
1020
+ DistributedType.MULTI_MUSA,
1021
+ DistributedType.MULTI_XPU,
1022
+ DistributedType.MULTI_HPU,
1023
+ )
1024
+ else False
1025
+ )
1026
+ args.tpu = defaults.distributed_type == DistributedType.XLA
1027
+ args.use_fsdp = defaults.distributed_type == DistributedType.FSDP
1028
+ args.use_megatron_lm = defaults.distributed_type == DistributedType.MEGATRON_LM
1029
+ args.tpu_use_cluster = defaults.tpu_use_cluster if args.tpu else False
1030
+ if args.gpu_ids is None:
1031
+ if defaults.gpu_ids is not None:
1032
+ args.gpu_ids = defaults.gpu_ids
1033
+ else:
1034
+ args.gpu_ids = "all"
1035
+
1036
+ if args.multi_gpu and args.num_machines is None:
1037
+ args.num_machines = defaults.num_machines
1038
+
1039
+ if len(args.gpu_ids.split(",")) < 2 and (args.gpu_ids != "all") and args.multi_gpu and args.num_machines <= 1:
1040
+ raise ValueError(
1041
+ "Less than two GPU ids were configured and tried to run on on multiple GPUs. "
1042
+ "Please ensure at least two are specified for `--gpu_ids`, or use `--gpu_ids='all'`."
1043
+ )
1044
+ if defaults.compute_environment == ComputeEnvironment.LOCAL_MACHINE:
1045
+ # Update args with the defaults
1046
+ for name, attr in defaults.__dict__.items():
1047
+ if isinstance(attr, dict):
1048
+ # Copy defaults.somedict.somearg to args.somearg and
1049
+ # defaults.fsdp_config.x to args.fsdp_x
1050
+ for key, value in attr.items():
1051
+ if name == "fsdp_config" and not key.startswith("fsdp"):
1052
+ key = "fsdp_" + key
1053
+ elif name == "fp8_config" and not key.startswith("fp8"):
1054
+ key = "fp8_" + key
1055
+ if hasattr(args, "nondefault") and key not in args.nondefault:
1056
+ setattr(args, key, value)
1057
+ elif (
1058
+ name not in ["compute_environment", "mixed_precision", "distributed_type"]
1059
+ and getattr(args, name, None) is None
1060
+ ):
1061
+ # Those args are handled separately
1062
+ setattr(args, name, attr)
1063
+ if not args.debug:
1064
+ args.debug = defaults.debug
1065
+
1066
+ if not args.mixed_precision:
1067
+ if defaults.mixed_precision is None:
1068
+ args.mixed_precision = "no"
1069
+ else:
1070
+ args.mixed_precision = defaults.mixed_precision
1071
+ mp_from_config_flag = True
1072
+ else:
1073
+ native_amp = is_bf16_available(True)
1074
+ if (
1075
+ args.mixed_precision == "bf16"
1076
+ and not native_amp
1077
+ and not (args.tpu and is_torch_xla_available(check_is_tpu=True))
1078
+ ):
1079
+ raise ValueError("bf16 mixed precision requires PyTorch >= 1.10 and a supported device.")
1080
+
1081
+ # Silently set the default here
1082
+ if args.dynamo_backend is None:
1083
+ args.dynamo_backend = "no"
1084
+ if args.num_processes == -1:
1085
+ raise ValueError("You need to manually pass in `--num_processes` using this config yaml.")
1086
+ else:
1087
+ if args.num_processes is None:
1088
+ if is_xpu_available():
1089
+ args.num_processes = torch.xpu.device_count()
1090
+ elif is_mlu_available():
1091
+ args.num_processes = torch.mlu.device_count()
1092
+ elif is_sdaa_available():
1093
+ args.num_processes = torch.sdaa.device_count()
1094
+ elif is_musa_available():
1095
+ args.num_processes = torch.musa.device_count()
1096
+ elif is_npu_available():
1097
+ args.num_processes = torch.npu.device_count()
1098
+ elif is_hpu_available():
1099
+ args.num_processes = torch.hpu.device_count()
1100
+ else:
1101
+ args.num_processes = torch.cuda.device_count()
1102
+ warned.append(f"\t`--num_processes` was set to a value of `{args.num_processes}`")
1103
+ if args.debug is None:
1104
+ args.debug = False
1105
+ if (
1106
+ not args.multi_gpu
1107
+ and args.num_processes > 1
1108
+ and (
1109
+ (is_xpu_available() and torch.xpu.device_count() > 1)
1110
+ or (is_npu_available() and torch.npu.device_count() > 1)
1111
+ or (is_hpu_available() and torch.hpu.device_count() > 1)
1112
+ or (is_mlu_available() and torch.mlu.device_count() > 1)
1113
+ or (is_sdaa_available() and torch.sdaa.device_count() > 1)
1114
+ or (is_musa_available() and torch.musa.device_count() > 1)
1115
+ or (torch.cuda.is_available() and torch.cuda.device_count() > 1)
1116
+ )
1117
+ ):
1118
+ warned.append(
1119
+ "\t\tMore than one GPU was found, enabling multi-GPU training.\n"
1120
+ "\t\tIf this was unintended please pass in `--num_processes=1`."
1121
+ )
1122
+ args.multi_gpu = True
1123
+ if args.num_machines is None:
1124
+ warned.append("\t`--num_machines` was set to a value of `1`")
1125
+ args.num_machines = 1
1126
+ if args.mixed_precision is None:
1127
+ warned.append("\t`--mixed_precision` was set to a value of `'no'`")
1128
+ args.mixed_precision = "no"
1129
+ if not hasattr(args, "use_cpu"):
1130
+ args.use_cpu = args.cpu
1131
+ if args.dynamo_backend is None:
1132
+ warned.append("\t`--dynamo_backend` was set to a value of `'no'`")
1133
+ args.dynamo_backend = "no"
1134
+ if args.debug:
1135
+ logger.debug("Running script in debug mode, expect distributed operations to be slightly slower.")
1136
+
1137
+ is_aws_env_disabled = defaults is None or (
1138
+ defaults is not None and defaults.compute_environment != ComputeEnvironment.AMAZON_SAGEMAKER
1139
+ )
1140
+ if is_aws_env_disabled and args.num_cpu_threads_per_process is None:
1141
+ args.num_cpu_threads_per_process = get_int_from_env(["OMP_NUM_THREADS"], 1)
1142
+ if args.use_cpu and args.num_processes >= 1 and get_int_from_env(["OMP_NUM_THREADS"], 0) == 0:
1143
+ local_size = get_int_from_env(
1144
+ ["MPI_LOCALNRANKS", "OMPI_COMM_WORLD_LOCAL_SIZE", "MV2_COMM_WORLD_LOCAL_SIZE"],
1145
+ max(int(args.num_processes / args.num_machines), 1),
1146
+ )
1147
+ threads_per_process = int(psutil.cpu_count(logical=False) / local_size)
1148
+ if threads_per_process > 1:
1149
+ args.num_cpu_threads_per_process = threads_per_process
1150
+ warned.append(
1151
+ 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"
1152
+ )
1153
+
1154
+ if args.ipex is not None:
1155
+ logger.warning(
1156
+ "ipex flag is deprecated, will be removed in Accelerate v1.10. "
1157
+ "From 2.7.0, PyTorch has all needed optimizations for Intel CPU and XPU."
1158
+ )
1159
+
1160
+ if args.use_xpu is not None:
1161
+ logger.warning(
1162
+ "use_xpu is deprecated and ignored, will be removed in Accelerate v1.20. "
1163
+ "XPU is a PyTorch native citizen now, we don't need extra argument to enable it any more."
1164
+ )
1165
+
1166
+ if any(warned):
1167
+ message = "The following values were not passed to `accelerate launch` and had defaults used instead:\n"
1168
+ message += "\n".join(warned)
1169
+ message += (
1170
+ "\nTo avoid this warning pass in values for each of the problematic parameters or run `accelerate config`."
1171
+ )
1172
+ logger.warning(message)
1173
+ return args, defaults, mp_from_config_flag
1174
+
1175
+
1176
+ def launch_command(args):
1177
+ args, defaults, mp_from_config_flag = _validate_launch_command(args)
1178
+ # Use the proper launcher
1179
+ if args.use_deepspeed and not args.cpu:
1180
+ args.deepspeed_fields_from_accelerate_config = list(defaults.deepspeed_config.keys()) if defaults else []
1181
+ if mp_from_config_flag:
1182
+ args.deepspeed_fields_from_accelerate_config.append("mixed_precision")
1183
+ args.deepspeed_fields_from_accelerate_config = ",".join(args.deepspeed_fields_from_accelerate_config)
1184
+ deepspeed_launcher(args)
1185
+ elif args.use_fsdp and not args.cpu:
1186
+ multi_gpu_launcher(args)
1187
+ elif args.use_megatron_lm and not args.cpu:
1188
+ multi_gpu_launcher(args)
1189
+ elif args.multi_gpu and not args.cpu:
1190
+ multi_gpu_launcher(args)
1191
+ elif args.tpu and not args.cpu:
1192
+ if args.tpu_use_cluster:
1193
+ tpu_pod_launcher(args)
1194
+ else:
1195
+ tpu_launcher(args)
1196
+ elif defaults is not None and defaults.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
1197
+ sagemaker_launcher(defaults, args)
1198
+ else:
1199
+ simple_launcher(args)
1200
+
1201
+
1202
+ def main():
1203
+ parser = launch_command_parser()
1204
+ args = parser.parse_args()
1205
+ launch_command(args)
1206
+
1207
+
1208
+ if __name__ == "__main__":
1209
+ main()
venv/lib/python3.10/site-packages/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
venv/lib/python3.10/site-packages/accelerate/commands/menu/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (231 Bytes). View file
 
venv/lib/python3.10/site-packages/accelerate/commands/menu/__pycache__/cursor.cpython-310.pyc ADDED
Binary file (1.42 kB). View file
 
venv/lib/python3.10/site-packages/accelerate/commands/menu/__pycache__/helpers.cpython-310.pyc ADDED
Binary file (1.64 kB). View file
 
venv/lib/python3.10/site-packages/accelerate/commands/menu/__pycache__/input.cpython-310.pyc ADDED
Binary file (2.34 kB). View file
 
venv/lib/python3.10/site-packages/accelerate/commands/menu/__pycache__/keymap.cpython-310.pyc ADDED
Binary file (2.39 kB). View file
 
venv/lib/python3.10/site-packages/accelerate/commands/menu/__pycache__/selection_menu.cpython-310.pyc ADDED
Binary file (4.43 kB). View file
 
venv/lib/python3.10/site-packages/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()
venv/lib/python3.10/site-packages/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)
venv/lib/python3.10/site-packages/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())
venv/lib/python3.10/site-packages/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"]
venv/lib/python3.10/site-packages/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
venv/lib/python3.10/site-packages/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()
venv/lib/python3.10/site-packages/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()
venv/lib/python3.10/site-packages/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)
venv/lib/python3.10/site-packages/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)
venv/lib/python3.10/site-packages/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