


# 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							:							Dict    							=					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							:							Any    							=					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							:							Dict    							=					default_yaml_config_file
else:
       __UpperCamelCase							:							Optional[int]    							=					default_json_config_file

def       _a	(					SCREAMING_SNAKE_CASE						:					str  ):







 """simple docstring"""



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

@dataclass
class    __magic_name__						:
     A:		ComputeEnvironment
     A:		Union[DistributedType, SageMakerDistributedType]
     A:		str
     A:		bool


     def   UpperCAmelCase__						(   self				:  int      )	->   Dict:





      '''simple docstring'''






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


     @classmethod
     def   UpperCAmelCase__						(   cls				:  Tuple				,						lowerCamelCase__				:  Any=None      )	->   Optional[Any]:





      '''simple docstring'''






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


     def   UpperCAmelCase__						(   self				:  Tuple				,						lowerCamelCase__				:  List[str]      )	->   List[Any]:





      '''simple docstring'''






      with open(lowerCamelCase__				,						'''w'''				,						encoding='''utf-8'''      ) as f:
       UpperCamelCase__       :     Optional[int] 							= json.dumps(self.to_dict()				,						indent=2				,						sort_keys=lowerCamelCase__      ) + '''\n'''
       f.write(lowerCamelCase__      )


     @classmethod
     def   UpperCAmelCase__						(   cls				:  Optional[Any]				,						lowerCamelCase__				:  Any=None      )	->   int:





      '''simple docstring'''






      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__       :     List[Any] 							= ComputeEnvironment.LOCAL_MACHINE

      if "mixed_precision" not in config_dict:
       UpperCamelCase__       :     int 							= '''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__       :     Dict 							= '''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__       :     Dict 							= config_dict.pop('''dynamo_backend'''      )
       UpperCamelCase__       :     Any 							= {} if dynamo_backend == '''NO''' else {'''dynamo_backend''': dynamo_backend}
      if "use_cpu" not in config_dict:
       UpperCamelCase__       :     Any 							= False
      return cls(**lowerCamelCase__      )


     def   UpperCAmelCase__						(   self				:  Optional[int]				,						lowerCamelCase__				:  int      )	->   Dict:





      '''simple docstring'''






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


     def   UpperCAmelCase__						(   self				:  Tuple      )	->   Dict:





      '''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__       :     Union[str, Any] 							= SageMakerDistributedType(self.distributed_type      )
       else:
        UpperCamelCase__       :     List[Any] 							= DistributedType(self.distributed_type      )
      if self.dynamo_config is None:
       UpperCamelCase__       :     Optional[Any] 							= {}



@dataclass
class    __magic_name__						(  __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   UpperCAmelCase__						(   self				:  Tuple      )	->   int:





      '''simple docstring'''






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



@dataclass
class    __magic_name__						(  __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






from typing import TYPE_CHECKING

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


__UpperCamelCase							:							List[Any]    							=					{
    "configuration_mpnet": ["MPNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "MPNetConfig"],
    "tokenization_mpnet": ["MPNetTokenizer"],
}

try:
       if not is_tokenizers_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       __UpperCamelCase							:							Union[str, Any]    							=					["MPNetTokenizerFast"]

try:
       if not is_torch_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       __UpperCamelCase							:							Union[str, Any]    							=					[
           "MPNET_PRETRAINED_MODEL_ARCHIVE_LIST",
           "MPNetForMaskedLM",
           "MPNetForMultipleChoice",
           "MPNetForQuestionAnswering",
           "MPNetForSequenceClassification",
           "MPNetForTokenClassification",
           "MPNetLayer",
           "MPNetModel",
           "MPNetPreTrainedModel",
       ]

try:
       if not is_tf_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       __UpperCamelCase							:							List[Any]    							=					[
           "TF_MPNET_PRETRAINED_MODEL_ARCHIVE_LIST",
           "TFMPNetEmbeddings",
           "TFMPNetForMaskedLM",
           "TFMPNetForMultipleChoice",
           "TFMPNetForQuestionAnswering",
           "TFMPNetForSequenceClassification",
           "TFMPNetForTokenClassification",
           "TFMPNetMainLayer",
           "TFMPNetModel",
           "TFMPNetPreTrainedModel",
       ]


if TYPE_CHECKING:
       from .configuration_mpnet import MPNET_PRETRAINED_CONFIG_ARCHIVE_MAP, MPNetConfig
       from .tokenization_mpnet import MPNetTokenizer

       try:
              if not is_tokenizers_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .tokenization_mpnet_fast import MPNetTokenizerFast

       try:
              if not is_torch_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_mpnet import (
                  MPNET_PRETRAINED_MODEL_ARCHIVE_LIST,
                  MPNetForMaskedLM,
                  MPNetForMultipleChoice,
                  MPNetForQuestionAnswering,
                  MPNetForSequenceClassification,
                  MPNetForTokenClassification,
                  MPNetLayer,
                  MPNetModel,
                  MPNetPreTrainedModel,
              )

       try:
              if not is_tf_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_tf_mpnet import (
                  TF_MPNET_PRETRAINED_MODEL_ARCHIVE_LIST,
                  TFMPNetEmbeddings,
                  TFMPNetForMaskedLM,
                  TFMPNetForMultipleChoice,
                  TFMPNetForQuestionAnswering,
                  TFMPNetForSequenceClassification,
                  TFMPNetForTokenClassification,
                  TFMPNetMainLayer,
                  TFMPNetModel,
                  TFMPNetPreTrainedModel,
              )

else:
       import sys

       __UpperCamelCase							:							Tuple    							=					_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)


