





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


lowercase_		:					Dict      						=    '''Create a default config file for Accelerate with only a few flags set.'''

def    A__(		__lowerCAmelCase="no"						,      __lowerCAmelCase = default_json_config_file						,      __lowerCAmelCase = False			):
				_snake_case			:      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
				_snake_case			:      Optional[Any]	    = 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}'''			)
				_snake_case			:      Any	    = {
				    """compute_environment""": """LOCAL_MACHINE""",
				    """mixed_precision""": mixed_precision,
				}
				if torch.cuda.is_available():
								_snake_case			:      Any	    = torch.cuda.device_count()
								_snake_case			:      Union[str, Any]	    = num_gpus
								_snake_case			:      Union[str, Any]	    = False
								if num_gpus > 1:
												_snake_case			:      Optional[Any]	    = """MULTI_GPU"""
								else:
												_snake_case			:      Dict	    = """NO"""
				elif is_xpu_available() and use_xpu:
								_snake_case			:      str	    = torch.xpu.device_count()
								_snake_case			:      str	    = num_xpus
								_snake_case			:      List[Any]	    = False
								if num_xpus > 1:
												_snake_case			:      int	    = """MULTI_XPU"""
								else:
												_snake_case			:      Optional[int]	    = """NO"""
				elif is_npu_available():
								_snake_case			:      Optional[Any]	    = torch.npu.device_count()
								_snake_case			:      int	    = num_npus
								_snake_case			:      Any	    = False
								if num_npus > 1:
												_snake_case			:      int	    = """MULTI_NPU"""
								else:
												_snake_case			:      List[Any]	    = """NO"""
				else:
								_snake_case			:      Optional[Any]	    = 0
								_snake_case			:      Optional[int]	    = True
								_snake_case			:      List[Any]	    = 1
								_snake_case			:      Optional[Any]	    = """NO"""
				_snake_case			:      Optional[int]	    = ClusterConfig(**__lowerCAmelCase			)
				config.to_json_file(__lowerCAmelCase			)
				return path

def    A__(		__lowerCAmelCase						,      __lowerCAmelCase			):
				_snake_case			:      Dict	    = 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    A__(		__lowerCAmelCase			):
				_snake_case			:      Optional[Any]	    = write_basic_config(args.mixed_precision						,      args.save_location			)
				if config_file:
								print(F'''accelerate configuration saved at {config_file}'''			)







"""simple docstring"""



from typing import List

from .keymap import KEYMAP, get_character

def  _A(		lowerCAmelCase							):

							def decorator(lowerCAmelCase							):
														A__       :     Any								=			getattr(lowerCAmelCase			,  """handle_key"""			,  []							)
														handle += [key]
														setattr(lowerCAmelCase			,  """handle_key"""			,  lowerCAmelCase							)
														return func

							return decorator

def  _A(		*lowerCAmelCase							):

							def decorator(lowerCAmelCase							):
														A__       :     Optional[Any]								=			getattr(lowerCAmelCase			,  """handle_key"""			,  []							)
														handle += keys
														setattr(lowerCAmelCase			,  """handle_key"""			,  lowerCAmelCase							)
														return func

							return decorator
class 						__UpperCAmelCase    (__A     ):







			'''simple docstring'''





			def __new__(			cls   ,      snake_case_   ,      snake_case_   ,      snake_case_							):







										'''simple docstring'''


										A__       :     Union[str, Any]								=			super().__new__(cls   ,      snake_case_   ,      snake_case_   ,      snake_case_							)
										if not hasattr(snake_case_   ,      """key_handler"""							):
																	setattr(snake_case_   ,      """key_handler"""   ,      {}							)
										setattr(snake_case_   ,      """handle_input"""   ,      KeyHandler.handle_input							)

										for value in attrs.values():
																	A__       :     Dict								=			getattr(snake_case_   ,      """handle_key"""   ,      []							)
																	for key in handled_keys:
																								A__       :     Optional[Any]								=			value
										return new_cls





			@staticmethod
			def 		lowerCamelCase					(			cls							):







										'''simple docstring'''


										A__       :     int								=			get_character()
										if char != KEYMAP["undefined"]:
																	A__       :     Union[str, Any]								=			ord(snake_case_							)
										A__       :     int								=			cls.key_handler.get(snake_case_							)
										if handler:
																	A__       :     int								=			char
																	return handler(cls							)
										else:
																	return None





def  _A(		cls							):
							return KeyHandler(cls.__name__			,  cls.__bases__			,  cls.__dict__.copy()							)





