

"""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


lowerCamelCase__			:					int							  =					os.path.expanduser(
    os.getenv('''HF_HOME''', os.path.join(os.getenv('''XDG_CACHE_HOME''', '''~/.cache'''), '''huggingface'''))
)
lowerCamelCase__			:					List[str]							  =					os.path.join(hf_cache_home, '''accelerate''')
lowerCamelCase__			:					Dict							  =					os.path.join(cache_dir, '''default_config.yaml''')
lowerCamelCase__			:					Tuple							  =					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):
							lowerCamelCase__			:					Union[str, Any]							  =					default_yaml_config_file
else:
							lowerCamelCase__			:					Optional[int]							  =					default_json_config_file
def  UpperCamelCase   (     _lowerCAmelCase       :  Tuple	)			->     Optional[Any]:


	if config_file is not None:
		if not os.path.isfile(_A	):
			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      :							List[str]       =   default_config_file
	with open(_A,					"""r""",					encoding="""utf-8"""	) as f:
		if config_file.endswith(""".json"""	):
			if (
			    json.load(_A	).get("""compute_environment""",					ComputeEnvironment.LOCAL_MACHINE	)
			    == ComputeEnvironment.LOCAL_MACHINE
			):
				_UpperCAmelCase      :							int       =   ClusterConfig
			else:
				_UpperCAmelCase      :							List[Any]       =   SageMakerConfig
			return config_class.from_json_file(json_file=_A	)
		else:
			if (
			    yaml.safe_load(_A	).get("""compute_environment""",					ComputeEnvironment.LOCAL_MACHINE	)
			    == ComputeEnvironment.LOCAL_MACHINE
			):
				_UpperCAmelCase      :							Union[str, Any]       =   ClusterConfig
			else:
				_UpperCAmelCase      :							Dict       =   SageMakerConfig
			return config_class.from_yaml_file(yaml_file=_A	)






@dataclass
class       _UpperCAmelCase     :
			__a	:    ComputeEnvironment
			__a	:    Union[DistributedType, SageMakerDistributedType]
			__a	:    str
			__a	:    bool
			def 							__snake_case	(						self       )      ->      Union[str, Any]:






				'''simple docstring'''







				_UpperCAmelCase      :							Tuple       =   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      :							Any       =   value.value
					if isinstance(__lowerCAmelCase ,						__lowerCAmelCase       ) and not bool(__lowerCAmelCase       ):
						_UpperCAmelCase      :							Dict       =   None
				_UpperCAmelCase      :							List[Any]       =   {k: v for k, v in result.items() if v is not None}
				return result
			@classmethod
			def 							__snake_case	(						cls ,						_A=None       )      ->      Union[str, Any]:






				'''simple docstring'''







				_UpperCAmelCase      :							int       =   default_json_config_file if json_file is None else json_file
				with open(__lowerCAmelCase ,						"""r""" ,						encoding="""utf-8"""       ) as f:
					_UpperCAmelCase      :							Optional[Any]       =   json.load(__lowerCAmelCase       )
				if "compute_environment" not in config_dict:
					_UpperCAmelCase      :							Optional[int]       =   ComputeEnvironment.LOCAL_MACHINE
				if "mixed_precision" not in config_dict:
					_UpperCAmelCase      :							Optional[Any]       =   """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      :							Any       =   config_dict.pop("""dynamo_backend"""       )
					_UpperCAmelCase      :							Any       =   {} if dynamo_backend == """NO""" else {"""dynamo_backend""": dynamo_backend}
				if "use_cpu" not in config_dict:
					_UpperCAmelCase      :							Optional[int]       =   False
				return cls(**__lowerCAmelCase       )
			def 							__snake_case	(						self ,						_A       )      ->      Union[str, Any]:






				'''simple docstring'''







				with open(__lowerCAmelCase ,						"""w""" ,						encoding="""utf-8"""       ) as f:
					_UpperCAmelCase      :							Dict       =   json.dumps(self.to_dict() ,						indent=2 ,						sort_keys=__lowerCAmelCase       ) + """\n"""
					f.write(__lowerCAmelCase       )
			@classmethod
			def 							__snake_case	(						cls ,						_A=None       )      ->      List[Any]:






				'''simple docstring'''







				_UpperCAmelCase      :							Tuple       =   default_yaml_config_file if yaml_file is None else yaml_file
				with open(__lowerCAmelCase ,						"""r""" ,						encoding="""utf-8"""       ) as f:
					_UpperCAmelCase      :							int       =   yaml.safe_load(__lowerCAmelCase       )
				if "compute_environment" not in config_dict:
					_UpperCAmelCase      :							List[Any]       =   ComputeEnvironment.LOCAL_MACHINE

				if "mixed_precision" not in config_dict:
					_UpperCAmelCase      :							Union[str, Any]       =   """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      :							Optional[int]       =   """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      :							int       =   config_dict.pop("""dynamo_backend"""       )
					_UpperCAmelCase      :							Tuple       =   {} if dynamo_backend == """NO""" else {"""dynamo_backend""": dynamo_backend}
				if "use_cpu" not in config_dict:
					_UpperCAmelCase      :							Tuple       =   False
				return cls(**__lowerCAmelCase       )
			def 							__snake_case	(						self ,						_A       )      ->      Optional[int]:






				'''simple docstring'''







				with open(__lowerCAmelCase ,						"""w""" ,						encoding="""utf-8"""       ) as f:
					yaml.safe_dump(self.to_dict() ,						__lowerCAmelCase       )
			def 							__snake_case	(						self       )      ->      str:






				'''simple docstring'''







				if isinstance(self.compute_environment ,						__lowerCAmelCase       ):
					_UpperCAmelCase      :							Dict       =   ComputeEnvironment(self.compute_environment       )
				if isinstance(self.distributed_type ,						__lowerCAmelCase       ):
					if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
						_UpperCAmelCase      :							int       =   SageMakerDistributedType(self.distributed_type       )
					else:
						_UpperCAmelCase      :							Optional[Any]       =   DistributedType(self.distributed_type       )
				if self.dynamo_config is None:
					_UpperCAmelCase      :							str       =   {}






@dataclass
class       _UpperCAmelCase     (						lowerCAmelCase__):
			__a	:    int
			__a	:    int			   =							0
			__a	:    int			   =							1
			__a	:    Optional[str]			   =							None
			__a	:    Optional[str]			   =							None
			__a	:    Optional[int]			   =							None
			__a	:    Optional[str]			   =							"static"
			__a	:    Optional[bool]			   =							False
			__a	:    str			   =							"main"

			# args for deepspeed_plugin
			__a	:    dict			   =							None
			# args for fsdp
			__a	:    dict			   =							None
			# args for megatron_lm
			__a	:    dict			   =							None
			# args for ipex
			__a	:    dict			   =							None
			# args for TPU
			__a	:    bool			   =							False

			# args for TPU pods
			__a	:    str			   =							None
			__a	:    str			   =							None
			__a	:    bool			   =							False
			__a	:    bool			   =							False
			__a	:    str			   =							None
			__a	:    List[str]			   =							None
			__a	:    List[str]			   =							None
			__a	:    List[str]			   =							None

			# args for dynamo
			__a	:    dict			   =							None
			def 							__snake_case	(						self       )      ->      List[Any]:






				'''simple docstring'''







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






@dataclass
class       _UpperCAmelCase     (						lowerCAmelCase__):
			__a	:    str
			__a	:    str
			__a	:    Optional[str]			   =							None
			__a	:    Optional[str]			   =							None
			__a	:    str			   =							"us-east-1"
			__a	:    int			   =							1
			__a	:    str			   =							"all"
			__a	:    str			   =							f"accelerate-sagemaker-{num_machines}"
			__a	:    str			   =							SAGEMAKER_PYTORCH_VERSION
			__a	:    str			   =							SAGEMAKER_TRANSFORMERS_VERSION
			__a	:    str			   =							SAGEMAKER_PYTHON_VERSION
			__a	:    str			   =							None
			__a	:    str			   =							None
			__a	:    dict			   =							None
			__a	:    dict			   =							None








"""simple docstring"""






from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tf_available,
    is_torch_available,
)


lowerCamelCase__			:					Union[str, Any]							  =					{
    '''configuration_unispeech_sat''': ['''UNISPEECH_SAT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''UniSpeechSatConfig'''],
}

try:
						if not is_torch_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						lowerCamelCase__			:					List[str]							  =					[
						    '''UNISPEECH_SAT_PRETRAINED_MODEL_ARCHIVE_LIST''',
						    '''UniSpeechSatForAudioFrameClassification''',
						    '''UniSpeechSatForCTC''',
						    '''UniSpeechSatForPreTraining''',
						    '''UniSpeechSatForSequenceClassification''',
						    '''UniSpeechSatForXVector''',
						    '''UniSpeechSatModel''',
						    '''UniSpeechSatPreTrainedModel''',
						]

if TYPE_CHECKING:
						from .configuration_unispeech_sat import UNISPEECH_SAT_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechSatConfig

						try:
												if not is_torch_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .modeling_unispeech_sat import (
												    UNISPEECH_SAT_PRETRAINED_MODEL_ARCHIVE_LIST,
												    UniSpeechSatForAudioFrameClassification,
												    UniSpeechSatForCTC,
												    UniSpeechSatForPreTraining,
												    UniSpeechSatForSequenceClassification,
												    UniSpeechSatForXVector,
												    UniSpeechSatModel,
												    UniSpeechSatPreTrainedModel,
												)

else:
						import sys

						lowerCamelCase__			:					Any							  =					_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)





