



# 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


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


def 	_A	(   _UpperCamelCase			):
				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						:  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						:  str     					=	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						:  Tuple     					=	ClusterConfig
												else:
																_UpperCAmelCase						:  Optional[Any]     					=	SageMakerConfig
												return config_class.from_yaml_file(yaml_file=__A			)





@dataclass
class 							lowerCAmelCase_		:
		SCREAMING_SNAKE_CASE_       :			int					       =	4_2
		SCREAMING_SNAKE_CASE_       :			Dict					       =	4_2
		SCREAMING_SNAKE_CASE_       :			str					       =	4_2
		SCREAMING_SNAKE_CASE_       :			Tuple					       =	4_2







		def 					a_  (    self  :   str					)       ->		Any:


						'''simple docstring'''







						_UpperCAmelCase						:  List[str]     					=	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						:  Union[str, Any]     					=	None
						_UpperCAmelCase						:  Optional[int]     					=	{k: v for k, v in result.items() if v is not None}
						return result







		@classmethod
		def 					a_  (    cls  :   List[str]       ,		UpperCAmelCase_  :   str=None					)       ->		str:


						'''simple docstring'''







						_UpperCAmelCase						:  Union[str, Any]     					=	default_json_config_file if json_file is None else json_file
						with open(lowerCAmelCase__       ,		'''r'''       ,		encoding='''utf-8'''					) as f:
										_UpperCAmelCase						:  Optional[int]     					=	json.load(lowerCAmelCase__					)
						if "compute_environment" not in config_dict:
										_UpperCAmelCase						:  Dict     					=	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 "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						:  Optional[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 					a_  (    self  :   Optional[int]       ,		UpperCAmelCase_  :   Optional[int]					)       ->		Any:


						'''simple docstring'''







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







		@classmethod
		def 					a_  (    cls  :   List[Any]       ,		UpperCAmelCase_  :   List[str]=None					)       ->		Union[str, Any]:


						'''simple docstring'''







						_UpperCAmelCase						:  int     					=	default_yaml_config_file if yaml_file is None else yaml_file
						with open(lowerCAmelCase__       ,		'''r'''       ,		encoding='''utf-8'''					) as f:
										_UpperCAmelCase						:  Optional[Any]     					=	yaml.safe_load(lowerCAmelCase__					)
						if "compute_environment" not in config_dict:
										_UpperCAmelCase						:  str     					=	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 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						:  Optional[Any]     					=	{} if dynamo_backend == '''NO''' else {'''dynamo_backend''': dynamo_backend}
						if "use_cpu" not in config_dict:
										_UpperCAmelCase						:  Optional[Any]     					=	False
						return cls(**lowerCAmelCase__					)







		def 					a_  (    self  :   int       ,		UpperCAmelCase_  :   List[Any]					)       ->		Dict:


						'''simple docstring'''







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







		def 					a_  (    self  :   int					)       ->		int:


						'''simple docstring'''







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





@dataclass
class 							lowerCAmelCase_		(		_snake_case     ):
		SCREAMING_SNAKE_CASE_       :			int					       =	4_2
		SCREAMING_SNAKE_CASE_       :			Dict					       =	0
		SCREAMING_SNAKE_CASE_       :			List[Any]					       =	1
		SCREAMING_SNAKE_CASE_       :			Optional[int]					       =	None
		SCREAMING_SNAKE_CASE_       :			Optional[int]					       =	None
		SCREAMING_SNAKE_CASE_       :			Tuple					       =	None
		SCREAMING_SNAKE_CASE_       :			str					       =	"""static"""
		SCREAMING_SNAKE_CASE_       :			Optional[Any]					       =	False
		SCREAMING_SNAKE_CASE_       :			Any					       =	"""main"""

		# args for deepspeed_plugin
		SCREAMING_SNAKE_CASE_       :			Dict					       =	None
		# args for fsdp
		SCREAMING_SNAKE_CASE_       :			Optional[Any]					       =	None
		# args for megatron_lm
		SCREAMING_SNAKE_CASE_       :			str					       =	None
		# args for ipex
		SCREAMING_SNAKE_CASE_       :			Optional[Any]					       =	None
		# args for TPU
		SCREAMING_SNAKE_CASE_       :			Optional[Any]					       =	False

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

		# args for dynamo
		SCREAMING_SNAKE_CASE_       :			List[str]					       =	None







		def 					a_  (    self  :   str					)       ->		Dict:


						'''simple docstring'''







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





@dataclass
class 							lowerCAmelCase_		(		_snake_case     ):
		SCREAMING_SNAKE_CASE_       :			Dict					       =	4_2
		SCREAMING_SNAKE_CASE_       :			List[str]					       =	4_2
		SCREAMING_SNAKE_CASE_       :			int					       =	None
		SCREAMING_SNAKE_CASE_       :			int					       =	None
		SCREAMING_SNAKE_CASE_       :			List[Any]					       =	"""us-east-1"""
		SCREAMING_SNAKE_CASE_       :			List[str]					       =	1
		SCREAMING_SNAKE_CASE_       :			str					       =	"""all"""
		SCREAMING_SNAKE_CASE_       :			Any					       =	f"""accelerate-sagemaker-{num_machines}"""
		SCREAMING_SNAKE_CASE_       :			Dict					       =	SAGEMAKER_PYTORCH_VERSION
		SCREAMING_SNAKE_CASE_       :			Tuple					       =	SAGEMAKER_TRANSFORMERS_VERSION
		SCREAMING_SNAKE_CASE_       :			str					       =	SAGEMAKER_PYTHON_VERSION
		SCREAMING_SNAKE_CASE_       :			str					       =	None
		SCREAMING_SNAKE_CASE_       :			Tuple					       =	None
		SCREAMING_SNAKE_CASE_       :			Any					       =	None
		SCREAMING_SNAKE_CASE_       :			List[Any]					       =	None



from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available


lowerCAmelCase__							=			{
    "configuration_xlm_prophetnet": ["XLM_PROPHETNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "XLMProphetNetConfig"],
}

try:
      if not is_sentencepiece_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      lowerCAmelCase__							=			["XLMProphetNetTokenizer"]

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      lowerCAmelCase__							=			[
          "XLM_PROPHETNET_PRETRAINED_MODEL_ARCHIVE_LIST",
          "XLMProphetNetDecoder",
          "XLMProphetNetEncoder",
          "XLMProphetNetForCausalLM",
          "XLMProphetNetForConditionalGeneration",
          "XLMProphetNetModel",
          "XLMProphetNetPreTrainedModel",
      ]


if TYPE_CHECKING:
      from .configuration_xlm_prophetnet import XLM_PROPHETNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMProphetNetConfig

      try:
            if not is_sentencepiece_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .tokenization_xlm_prophetnet import XLMProphetNetTokenizer

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_xlm_prophetnet import (
                XLM_PROPHETNET_PRETRAINED_MODEL_ARCHIVE_LIST,
                XLMProphetNetDecoder,
                XLMProphetNetEncoder,
                XLMProphetNetForCausalLM,
                XLMProphetNetForConditionalGeneration,
                XLMProphetNetModel,
                XLMProphetNetPreTrainedModel,
            )

else:
      import sys

      lowerCAmelCase__							=			_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)



