"""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         =		os.path.expanduser(
    os.getenv("HF_HOME", os.path.join(os.getenv("XDG_CACHE_HOME", "~/.cache"), "huggingface"))
)
_UpperCamelCase         =		os.path.join(hf_cache_home, "accelerate")
_UpperCamelCase         =		os.path.join(cache_dir, "default_config.yaml")
_UpperCamelCase         =		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         =		default_yaml_config_file
else:
				_UpperCamelCase         =		default_json_config_file
def    _A(		lowerCAmelCase       ):
							if config_file is not None:
														if not os.path.isfile(lowerCAmelCase       ):
																					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:
														A__					:    Dict														= default_config_file
							with open(lowerCAmelCase ,     """r""" ,     encoding="""utf-8"""       ) as f:
														if config_file.endswith(""".json"""       ):
																					if (
																					    json.load(lowerCAmelCase       ).get("""compute_environment""" ,     ComputeEnvironment.LOCAL_MACHINE       )
																					    == ComputeEnvironment.LOCAL_MACHINE
																					):
																												A__					:    List[str]														= ClusterConfig
																					else:
																												A__					:    List[str]														= SageMakerConfig
																					return config_class.from_json_file(json_file=lowerCAmelCase       )
														else:
																					if (
																					    yaml.safe_load(lowerCAmelCase       ).get("""compute_environment""" ,     ComputeEnvironment.LOCAL_MACHINE       )
																					    == ComputeEnvironment.LOCAL_MACHINE
																					):
																												A__					:    Tuple														= ClusterConfig
																					else:
																												A__					:    Dict														= SageMakerConfig
																					return config_class.from_yaml_file(yaml_file=lowerCAmelCase       )
@dataclass
class 	__UpperCAmelCase						:







			'''simple docstring'''
			_UpperCamelCase     :	str				    =							42
			_UpperCamelCase     :	Dict				    =							42
			_UpperCamelCase     :	Optional[int]				    =							42
			_UpperCamelCase     :	str				    =							42





			def 		lowerCamelCase				( self       ):







										'''simple docstring'''


										A__					:    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(__A      ,			__A       ):
																								A__					:    List[str]														= value.value
																	if isinstance(__A      ,			__A       ) and not bool(__A       ):
																								A__					:    Any														= None
										A__					:    int														= {k: v for k, v in result.items() if v is not None}
										return result





			@classmethod
			def 		lowerCamelCase				( cls      ,			snake_case_=None       ):







										'''simple docstring'''


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





			def 		lowerCamelCase				( self      ,			snake_case_       ):







										'''simple docstring'''


										with open(__A      ,			"""w"""      ,			encoding="""utf-8"""       ) as f:
																	A__					:    Any														= json.dumps(self.to_dict()      ,			indent=2      ,			sort_keys=__A       ) + """\n"""
																	f.write(__A       )





			@classmethod
			def 		lowerCamelCase				( cls      ,			snake_case_=None       ):







										'''simple docstring'''


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

										if "mixed_precision" not in config_dict:
																	A__					:    Union[str, Any]														= """fp16""" if ("""fp16""" in config_dict and config_dict["""fp16"""]) else None
										if isinstance(config_dict["""mixed_precision"""]      ,			__A       ) and not config_dict["mixed_precision"]:
																	A__					:    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.
																	A__					:    Optional[Any]														= config_dict.pop("""dynamo_backend"""       )
																	A__					:    Dict														= {} if dynamo_backend == """NO""" else {"""dynamo_backend""": dynamo_backend}
										if "use_cpu" not in config_dict:
																	A__					:    Optional[Any]														= False
										return cls(**__A       )





			def 		lowerCamelCase				( self      ,			snake_case_       ):







										'''simple docstring'''


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





			def 		lowerCamelCase				( self       ):







										'''simple docstring'''


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





@dataclass
class 	__UpperCAmelCase						(_SCREAMING_SNAKE_CASE    ):







			'''simple docstring'''
			_UpperCamelCase     :	Dict				    =							42
			_UpperCamelCase     :	Optional[Any]				    =							0
			_UpperCamelCase     :	Union[str, Any]				    =							1
			_UpperCamelCase     :	Dict				    =							None
			_UpperCamelCase     :	Any				    =							None
			_UpperCamelCase     :	Union[str, Any]				    =							None
			_UpperCamelCase     :	List[Any]				    =							'static'
			_UpperCamelCase     :	int				    =							False
			_UpperCamelCase     :	Any				    =							'main'

			# args for deepspeed_plugin
			_UpperCamelCase     :	Tuple				    =							None
			# args for fsdp
			_UpperCamelCase     :	Tuple				    =							None
			# args for megatron_lm
			_UpperCamelCase     :	Optional[int]				    =							None
			# args for ipex
			_UpperCamelCase     :	Optional[Any]				    =							None
			# args for TPU
			_UpperCamelCase     :	str				    =							False

			# args for TPU pods
			_UpperCamelCase     :	Any				    =							None
			_UpperCamelCase     :	Union[str, Any]				    =							None
			_UpperCamelCase     :	List[Any]				    =							False
			_UpperCamelCase     :	Dict				    =							False
			_UpperCamelCase     :	Any				    =							None
			_UpperCamelCase     :	Union[str, Any]				    =							None
			_UpperCamelCase     :	Dict				    =							None
			_UpperCamelCase     :	List[Any]				    =							None

			# args for dynamo
			_UpperCamelCase     :	Any				    =							None





			def 		lowerCamelCase				( self       ):







										'''simple docstring'''


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





@dataclass
class 	__UpperCAmelCase						(_SCREAMING_SNAKE_CASE    ):







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






"""simple docstring"""



import enum
import inspect
import warnings
from functools import wraps
from typing import Callable, Optional

from .logging import get_logger


_UpperCamelCase         =		set()
_UpperCamelCase         =		get_logger(__name__)

def    _A(		lowerCAmelCase = None       ):

							def decorator(lowerCAmelCase       ):
														global _emitted_deprecation_warnings

														if inspect.isclass(lowerCAmelCase       ):
																					A__					:    List[Any]														= deprecated_class_or_function.__init__
																					A__					:    Any														= deprecated_class_or_function.__name__
														else:
																					A__					:    Dict														= deprecated_class_or_function
																					A__					:    Optional[int]														= deprecated_function.__name__
																					# Support deprecating __init__ class method: class name instead
																					A__					:    List[str]														= name if name != """__init__""" else deprecated_function.__qualname__.split("""."""       )[-2]

														A__					:    Union[str, Any]														= (
														    F'''{name} is deprecated and will be removed in the next major version of datasets.''' + F''' {help_message}'''
														    if help_message
														    else """"""
														)

														@wraps(lowerCAmelCase       )
														def wrapper(*lowerCAmelCase ,     **lowerCAmelCase       ):
																					A__					:    Tuple														= hash(lowerCAmelCase       )
																					if func_hash not in _emitted_deprecation_warnings:
																												warnings.warn(lowerCAmelCase ,     category=lowerCAmelCase ,     stacklevel=2       )
																												_emitted_deprecation_warnings.add(lowerCAmelCase       )
																					return deprecated_function(*lowerCAmelCase ,     **lowerCAmelCase       )

														A__					:    int														= """deprecated"""

														if inspect.isclass(lowerCAmelCase       ):
																					A__					:    Union[str, Any]														= wrapper
																					return deprecated_class_or_function
														else:
																					return wrapper

							return decorator
class 	__UpperCAmelCase						(enum.EnumMeta    ):







			'''simple docstring'''





			def __getattribute__( cls      ,			snake_case_       ):







										'''simple docstring'''


										A__					:    Union[str, Any]														= super().__getattribute__(snake_case_       )
										if isinstance(snake_case_      ,			enum.Enum       ) and obj._on_access:
																	obj._on_access()
										return obj





			def __getitem__( cls      ,			snake_case_       ):







										'''simple docstring'''


										A__					:    Tuple														= super().__getitem__(snake_case_       )
										if member._on_access:
																	member._on_access()
										return member





			def __call__( cls      ,			snake_case_      ,			snake_case_=None      ,			*, snake_case_=None      ,			snake_case_=None      ,			snake_case_=None      ,			snake_case_=1       ):







										'''simple docstring'''


										A__					:    List[Any]														= super().__call__(snake_case_      ,			snake_case_      ,			module=snake_case_      ,			qualname=snake_case_      ,			type=snake_case_      ,			start=snake_case_       )
										if isinstance(snake_case_      ,			enum.Enum       ) and obj._on_access:
																	obj._on_access()
										return obj





class 	__UpperCAmelCase						(enum.Enum       ,      metaclass=__A    ):







			'''simple docstring'''





			def __new__( cls      ,			snake_case_       ):







										'''simple docstring'''


										A__					:    Tuple														= object.__new__(cls       )
										A__					:    int														= value
										A__					:    Optional[int]														= member.deprecate
										return member





			@property
			def 		lowerCamelCase				( self       ):







										'''simple docstring'''


										return ""





			def 		lowerCamelCase				( self       ):







										'''simple docstring'''


										A__					:    Tuple														= F''' {self.help_message}''' if self.help_message else """"""
										warnings.warn(
										    F'''\'{self.__objclass__.__name__}\' is deprecated and will be removed in the next major version of datasets.'''
										    + help_message      ,			snake_case_      ,			stacklevel=3      ,			)





