


'''simple docstring'''



# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from pathlib import Path

import torch

from ...utils import is_npu_available, is_xpu_available
from .config_args import ClusterConfig, default_json_config_file
from .config_utils import SubcommandHelpFormatter


__A		='''Create a default config file for Accelerate with only a few flags set.'''







def 			_UpperCamelCase					(						UpperCamelCase__="no"       ,					UpperCamelCase__ = default_json_config_file       ,					UpperCamelCase__ = False    ):
			UpperCAmelCase__     :    Dict         =   Path(__lowerCAmelCase    )
			path.parent.mkdir(parents=__lowerCAmelCase       ,					exist_ok=__lowerCAmelCase    )
			if path.exists():
						print(
						    f'''Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`.'''    )
						return False
			UpperCAmelCase__     :    Dict         =   mixed_precision.lower()
			if mixed_precision not in ["no", "fp16", "bf16", "fp8"]:
						raise ValueError(
						    f'''`mixed_precision` should be one of \'no\', \'fp16\', \'bf16\', or \'fp8\'. Received {mixed_precision}'''    )
			UpperCAmelCase__     :    Optional[Any]         =   {
			    """compute_environment""": """LOCAL_MACHINE""",
			    """mixed_precision""": mixed_precision,
			}
			if torch.cuda.is_available():
						UpperCAmelCase__     :    List[Any]         =   torch.cuda.device_count()
						UpperCAmelCase__     :    Dict         =   num_gpus
						UpperCAmelCase__     :    Union[str, Any]         =   False
						if num_gpus > 1:
									UpperCAmelCase__     :    Optional[Any]         =   """MULTI_GPU"""
						else:
									UpperCAmelCase__     :    int         =   """NO"""
			elif is_xpu_available() and use_xpu:
						UpperCAmelCase__     :    str         =   torch.xpu.device_count()
						UpperCAmelCase__     :    Tuple         =   num_xpus
						UpperCAmelCase__     :    Dict         =   False
						if num_xpus > 1:
									UpperCAmelCase__     :    int         =   """MULTI_XPU"""
						else:
									UpperCAmelCase__     :    Dict         =   """NO"""
			elif is_npu_available():
						UpperCAmelCase__     :    int         =   torch.npu.device_count()
						UpperCAmelCase__     :    int         =   num_npus
						UpperCAmelCase__     :    List[Any]         =   False
						if num_npus > 1:
									UpperCAmelCase__     :    Union[str, Any]         =   """MULTI_NPU"""
						else:
									UpperCAmelCase__     :    Optional[Any]         =   """NO"""
			else:
						UpperCAmelCase__     :    str         =   0
						UpperCAmelCase__     :    List[str]         =   True
						UpperCAmelCase__     :    Any         =   1
						UpperCAmelCase__     :    str         =   """NO"""
			UpperCAmelCase__     :    List[Any]         =   ClusterConfig(**__lowerCAmelCase    )
			config.to_json_file(__lowerCAmelCase    )
			return path







def 			_UpperCamelCase					(						UpperCamelCase__       ,					UpperCamelCase__    ):
			UpperCAmelCase__     :    List[str]         =   parser.add_parser("""default"""       ,					parents=__lowerCAmelCase       ,					help=__lowerCAmelCase       ,					formatter_class=__lowerCAmelCase    )
			parser.add_argument(
			    """--config_file"""       ,					default=__lowerCAmelCase       ,					help=(
			        """The path to use to store the config file. Will default to a file named default_config.yaml in the cache """
			        """location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have """
			        """such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed """
			        """with \'huggingface\'."""
			    )       ,					dest="""save_location"""       ,					)

			parser.add_argument(
			    """--mixed_precision"""       ,					choices=["""no""", """fp16""", """bf16"""]       ,					type=__lowerCAmelCase       ,					help="""Whether or not to use mixed precision training. """
			    """Choose between FP16 and BF16 (bfloat16) training. """
			    """BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later."""       ,					default="""no"""       ,					)
			parser.set_defaults(func=__lowerCAmelCase    )
			return parser







def 			_UpperCamelCase					(						UpperCamelCase__    ):
			UpperCAmelCase__     :    Optional[Any]         =   write_basic_config(args.mixed_precision       ,					args.save_location    )
			if config_file:
						print(f'''accelerate configuration saved at {config_file}'''    )



import sys

from .dependency_versions_table import deps
from .utils.versions import require_version, require_version_core


# define which module versions we always want to check at run time
# (usually the ones defined in `install_requires` in setup.py)
#
# order specific notes:
# - tqdm must be checked before tokenizers

snake_case							:       List[str]     			=      '''python tqdm regex requests packaging filelock numpy tokenizers'''.split()
if sys.version_info < (3, 7):
						pkgs_to_check_at_runtime.append('''dataclasses''')
if sys.version_info < (3, 8):
						pkgs_to_check_at_runtime.append('''importlib_metadata''')

for pkg in pkgs_to_check_at_runtime:
						if pkg in deps:
												if pkg == "tokenizers":
																		# must be loaded here, or else tqdm check may fail
																		from .utils import is_tokenizers_available

																		if not is_tokenizers_available():
																								continue  # not required, check version only if installed

												require_version_core(deps[pkg])
						else:
												raise ValueError(f"""can't find {pkg} in {deps.keys()}, check dependency_versions_table.py""")






def 							__lowercase   ( __lowerCAmelCase							:				Optional[Any]					,    __lowerCAmelCase							:				Tuple=None   ):
							require_version(deps[pkg]					,    __lowerCAmelCase   )




