
'''simple docstring'''

import json
import os
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

import yaml

from ...utils import ComputeEnvironment, DistributedType, SageMakerDistributedType
from ...utils.constants import SAGEMAKER_PYTHON_VERSION, SAGEMAKER_PYTORCH_VERSION, SAGEMAKER_TRANSFORMERS_VERSION


_UpperCAmelCase   :      Dict 						=  os.path.expanduser(
    os.getenv("""HF_HOME""", os.path.join(os.getenv("""XDG_CACHE_HOME""", """~/.cache"""), """huggingface"""))
)
_UpperCAmelCase   :      Union[str, Any] 						=  os.path.join(hf_cache_home, """accelerate""")
_UpperCAmelCase   :      List[str] 						=  os.path.join(cache_dir, """default_config.yaml""")
_UpperCAmelCase   :      List[str] 						=  os.path.join(cache_dir, """default_config.yaml""")

# For backward compatibility: the default config is the json one if it's the only existing file.
if os.path.isfile(default_yaml_config_file) or not os.path.isfile(default_json_config_file):
	_UpperCAmelCase   :      List[str] 						=  default_yaml_config_file
else:
	_UpperCAmelCase   :      Optional[int] 						=  default_json_config_file







def 						snake_case__	(      UpperCamelCase	) ->      Any:
		if config_file is not None:
				if not os.path.isfile(UpperCamelCase	):
						raise FileNotFoundError(
						    f'''The passed configuration file `{config_file}` does not exist. '''
						    '''Please pass an existing file to `accelerate launch`, or use the the default one '''
						    '''created through `accelerate config` and run `accelerate launch` '''
						    '''without the `--config_file` argument.'''	)
		else:
				_UpperCamelCase       : Union[str, Any]    =      default_config_file
		with open(UpperCamelCase			,'''r'''			,encoding='''utf-8'''	) as f:
				if config_file.endswith('''.json'''	):
						if (
						    json.load(UpperCamelCase	).get('''compute_environment'''			,ComputeEnvironment.LOCAL_MACHINE	)
						    == ComputeEnvironment.LOCAL_MACHINE
						):
								_UpperCamelCase       : List[Any]    =      ClusterConfig
						else:
								_UpperCamelCase       : Tuple    =      SageMakerConfig
						return config_class.from_json_file(json_file=UpperCamelCase	)
				else:
						if (
						    yaml.safe_load(UpperCamelCase	).get('''compute_environment'''			,ComputeEnvironment.LOCAL_MACHINE	)
						    == ComputeEnvironment.LOCAL_MACHINE
						):
								_UpperCamelCase       : str    =      ClusterConfig
						else:
								_UpperCamelCase       : Union[str, Any]    =      SageMakerConfig
						return config_class.from_yaml_file(yaml_file=UpperCamelCase	)

@dataclass
class 			UpperCAmelCase				:





		"""simple docstring"""





		A__  :   List[Any]          =    42
		A__  :   List[Any]          =    42
		A__  :   Any          =    42
		A__  :   str          =    42
		def _lowercase  (    self     )				->    int:
				_UpperCamelCase       : Union[str, Any]    =      self.__dict__
				# For serialization, it's best to convert Enums to strings (or their underlying value type).
				for key, value in result.items():
						if isinstance(_lowerCamelCase  ,					_lowerCamelCase     ):
								_UpperCamelCase       : List[str]    =      value.value
						if isinstance(_lowerCamelCase  ,					_lowerCamelCase     ) and not bool(_lowerCamelCase     ):
								_UpperCamelCase       : str    =      None
				_UpperCamelCase       : Union[str, Any]    =      {k: v for k, v in result.items() if v is not None}
				return result
		@classmethod
		def _lowercase  (    cls  ,					_snake_case=None     )				->    List[Any]:
				_UpperCamelCase       : Any    =      default_json_config_file if json_file is None else json_file
				with open(_lowerCamelCase  ,					'''r'''  ,					encoding='''utf-8'''     ) as f:
						_UpperCamelCase       : Any    =      json.load(_lowerCamelCase     )
				if "compute_environment" not in config_dict:
						_UpperCamelCase       : int    =      ComputeEnvironment.LOCAL_MACHINE
				if "mixed_precision" not in config_dict:
						_UpperCamelCase       : Tuple    =      """fp16""" if ("""fp16""" in config_dict and config_dict["""fp16"""]) else None
				if "fp16" in config_dict:  # Convert the config to the new format.
						del config_dict["fp16"]
				if "dynamo_backend" in config_dict:  # Convert the config to the new format.
						_UpperCamelCase       : Optional[Any]    =      config_dict.pop('''dynamo_backend'''     )
						_UpperCamelCase       : List[str]    =      {} if dynamo_backend == """NO""" else {"""dynamo_backend""": dynamo_backend}
				if "use_cpu" not in config_dict:
						_UpperCamelCase       : Optional[int]    =      False
				return cls(**_lowerCamelCase     )
		def _lowercase  (    self  ,					_snake_case     )				->    Dict:

				with open(_lowerCamelCase  ,					'''w'''  ,					encoding='''utf-8'''     ) as f:
						_UpperCamelCase       : List[Any]    =      json.dumps(self.to_dict()  ,					indent=2  ,					sort_keys=_lowerCamelCase     ) + """\n"""
						f.write(_lowerCamelCase     )
		@classmethod
		def _lowercase  (    cls  ,					_snake_case=None     )				->    Tuple:
				_UpperCamelCase       : Any    =      default_yaml_config_file if yaml_file is None else yaml_file
				with open(_lowerCamelCase  ,					'''r'''  ,					encoding='''utf-8'''     ) as f:
						_UpperCamelCase       : Any    =      yaml.safe_load(_lowerCamelCase     )
				if "compute_environment" not in config_dict:
						_UpperCamelCase       : Tuple    =      ComputeEnvironment.LOCAL_MACHINE

				if "mixed_precision" not in config_dict:
						_UpperCamelCase       : Dict    =      """fp16""" if ("""fp16""" in config_dict and config_dict["""fp16"""]) else None
				if isinstance(config_dict['''mixed_precision''']  ,					_lowerCamelCase     ) and not config_dict["mixed_precision"]:
						_UpperCamelCase       : List[str]    =      """no"""
				if "fp16" in config_dict:  # Convert the config to the new format.
						del config_dict["fp16"]
				if "dynamo_backend" in config_dict:  # Convert the config to the new format.
						_UpperCamelCase       : List[str]    =      config_dict.pop('''dynamo_backend'''     )
						_UpperCamelCase       : List[Any]    =      {} if dynamo_backend == """NO""" else {"""dynamo_backend""": dynamo_backend}
				if "use_cpu" not in config_dict:
						_UpperCamelCase       : Union[str, Any]    =      False
				return cls(**_lowerCamelCase     )
		def _lowercase  (    self  ,					_snake_case     )				->    Optional[int]:

				with open(_lowerCamelCase  ,					'''w'''  ,					encoding='''utf-8'''     ) as f:
						yaml.safe_dump(self.to_dict()  ,					_lowerCamelCase     )




		def _lowercase  (    self     )				->    Optional[int]:

				if isinstance(self.compute_environment  ,					_lowerCamelCase     ):
						_UpperCamelCase       : List[str]    =      ComputeEnvironment(self.compute_environment     )
				if isinstance(self.distributed_type  ,					_lowerCamelCase     ):
						if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
								_UpperCamelCase       : Optional[int]    =      SageMakerDistributedType(self.distributed_type     )
						else:
								_UpperCamelCase       : Union[str, Any]    =      DistributedType(self.distributed_type     )
				if self.dynamo_config is None:
						_UpperCamelCase       : Optional[Any]    =      {}







@dataclass
class 			UpperCAmelCase				(					lowerCAmelCase__ ):





		"""simple docstring"""





		A__  :   Union[str, Any]          =    42
		A__  :   List[Any]          =    0
		A__  :   Optional[int]          =    1
		A__  :   Any          =    None
		A__  :   List[str]          =    None
		A__  :   str          =    None
		A__  :   Any          =    'static'
		A__  :   str          =    False
		A__  :   int          =    'main'

		# args for deepspeed_plugin
		A__  :   int          =    None
		# args for fsdp
		A__  :   Tuple          =    None
		# args for megatron_lm
		A__  :   Union[str, Any]          =    None
		# args for ipex
		A__  :   int          =    None
		# args for TPU
		A__  :   Tuple          =    False

		# args for TPU pods
		A__  :   Any          =    None
		A__  :   List[str]          =    None
		A__  :   List[Any]          =    False
		A__  :   Dict          =    False
		A__  :   Tuple          =    None
		A__  :   Tuple          =    None
		A__  :   Optional[int]          =    None
		A__  :   List[Any]          =    None

		# args for dynamo
		A__  :   Optional[int]          =    None
		def _lowercase  (    self     )				->    List[Any]:

				if self.deepspeed_config is None:
						_UpperCamelCase       : str    =      {}
				if self.fsdp_config is None:
						_UpperCamelCase       : Any    =      {}
				if self.megatron_lm_config is None:
						_UpperCamelCase       : Union[str, Any]    =      {}
				if self.ipex_config is None:
						_UpperCamelCase       : Optional[int]    =      {}
				return super().__post_init__()







@dataclass
class 			UpperCAmelCase				(					lowerCAmelCase__ ):





		"""simple docstring"""





		A__  :   Tuple          =    42
		A__  :   List[Any]          =    42
		A__  :   int          =    None
		A__  :   List[str]          =    None
		A__  :   Optional[Any]          =    'us-east-1'
		A__  :   List[str]          =    1
		A__  :   str          =    'all'
		A__  :   Optional[Any]          =    F"""accelerate-sagemaker-{num_machines}"""
		A__  :   Tuple          =    SAGEMAKER_PYTORCH_VERSION
		A__  :   Union[str, Any]          =    SAGEMAKER_TRANSFORMERS_VERSION
		A__  :   List[Any]          =    SAGEMAKER_PYTHON_VERSION
		A__  :   Union[str, Any]          =    None
		A__  :   int          =    None
		A__  :   Any          =    None
		A__  :   Union[str, Any]          =    None





'''simple docstring'''

_UpperCAmelCase   :      Optional[int] 						=  """
# Transformers installation
! pip install transformers datasets evaluate
# To install from source instead of the last release, comment the command above and uncomment the following one.
# ! pip install git+https://github.com/huggingface/transformers.git
"""

_UpperCAmelCase   :      Union[str, Any] 						=  [{"""type""": """code""", """content""": INSTALL_CONTENT}]
_UpperCAmelCase   :      Union[str, Any] 						=  {
    """{processor_class}""": """FakeProcessorClass""",
    """{model_class}""": """FakeModelClass""",
    """{object_class}""": """FakeObjectClass""",
}





