

# 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.

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


__snake_case							:			str      		= os.path.expanduser(
    os.getenv("""HF_HOME""", os.path.join(os.getenv("""XDG_CACHE_HOME""", """~/.cache"""), """huggingface"""))
)
__snake_case							:			Any      		= os.path.join(hf_cache_home, """accelerate""")
__snake_case							:			Any      		= os.path.join(cache_dir, """default_config.yaml""")
__snake_case							:			Dict      		= 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):
						__snake_case							:			Union[str, Any]      		= default_yaml_config_file
else:
						__snake_case							:			Union[str, Any]      		= default_json_config_file


def 				_UpperCAmelCase							(	a__):

			'''simple docstring'''



			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:
						a_	:	Any          =   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
									):
												a_	:	Tuple          =   ClusterConfig
									else:
												a_	:	Union[str, 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
									):
												a_	:	Optional[Any]          =   ClusterConfig
									else:
												a_	:	Optional[int]          =   SageMakerConfig
									return config_class.from_yaml_file(yaml_file=a__)



@dataclass
class 					A__:
						"""simple docstring"""






						_A						:							ComputeEnvironment
						_A						:							Union[DistributedType, SageMakerDistributedType]
						_A						:							str
						_A						:							bool





						def  UpperCamelCase__				(						self						)    ->   Optional[int]:
									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(_lowercase     ,			_lowercase						):
															a_	:	Tuple          =   value.value
												if isinstance(_lowercase     ,			_lowercase						) and not bool(_lowercase						):
															a_	:	Dict          =   None
									a_	:	Optional[Any]          =   {k: v for k, v in result.items() if v is not None}
									return result





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





						def  UpperCamelCase__				(						self     ,			_lowercase						)    ->   int:






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





						@classmethod
						def  UpperCamelCase__				(						cls     ,			_lowercase=None						)    ->   List[Any]:
									a_	:	List[Any]          =   default_yaml_config_file if yaml_file is None else yaml_file
									with open(_lowercase     ,			"""r"""     ,			encoding="""utf-8"""						) as f:
												a_	:	Tuple          =   yaml.safe_load(_lowercase						)
									if "compute_environment" not in config_dict:
												a_	:	str          =   ComputeEnvironment.LOCAL_MACHINE

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





						def  UpperCamelCase__				(						self     ,			_lowercase						)    ->   List[str]:






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





						def  UpperCamelCase__				(						self						)    ->   Union[str, Any]:






									if isinstance(self.compute_environment     ,			_lowercase						):
												a_	:	str          =   ComputeEnvironment(self.compute_environment						)
									if isinstance(self.distributed_type     ,			_lowercase						):
												if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
															a_	:	str          =   SageMakerDistributedType(self.distributed_type						)
												else:
															a_	:	Dict          =   DistributedType(self.distributed_type						)
									if self.dynamo_config is None:
												a_	:	Dict          =   {}







@dataclass
class 					A__(a_       ):
						"""simple docstring"""






						_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  UpperCamelCase__				(						self						)    ->   Tuple:






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







@dataclass
class 					A__(a_       ):
						"""simple docstring"""






						_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





from dataclasses import dataclass
from typing import Callable, Optional

import datasets



@dataclass
class 					A__(datasets.BuilderConfig       ):
						"""simple docstring"""






						_A						:							Optional[Callable]									= None
						_A						:							Optional[dict]									= None
						_A						:							Optional[datasets.Features]									= None





						def  UpperCamelCase__				(						self						)    ->   Tuple:
									assert self.generator is not None, "generator must be specified"

									if self.gen_kwargs is None:
												a_	:	Tuple          =   {}







class 					A__(datasets.GeneratorBasedBuilder       ):
						"""simple docstring"""






						_A						:							Dict									= GeneratorConfig





						def  UpperCamelCase__				(						self						)    ->   List[Any]:
									return datasets.DatasetInfo(features=self.config.features						)





						def  UpperCamelCase__				(						self     ,			_lowercase						)    ->   List[Any]:
									return [datasets.SplitGenerator(name=datasets.Split.TRAIN     ,			gen_kwargs=self.config.gen_kwargs						)]





						def  UpperCamelCase__				(						self     ,			**_lowercase						)    ->   Tuple:
									for idx, ex in enumerate(self.config.generator(**_lowercase						)						):
												yield idx, ex


