





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




@dataclass
class 				_lowerCamelCase :



      """simple docstring"""






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







      def 						UpperCAmelCase		( self   )       ->   Optional[int]:






        '''simple docstring'''






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







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






        '''simple docstring'''






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







      def 						UpperCAmelCase		( self				,						UpperCAmelCase   )       ->   int:






        '''simple docstring'''






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







      @classmethod
      def 						UpperCAmelCase		( cls				,						UpperCAmelCase=None   )       ->   List[Any]:






        '''simple docstring'''






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

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







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






        '''simple docstring'''






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







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






        '''simple docstring'''






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




@dataclass
class 				_lowerCamelCase (    a    ):



      """simple docstring"""






      UpperCAmelCase_						:      int
      UpperCAmelCase_						:      int       =0
      UpperCAmelCase_						:      int       =1
      UpperCAmelCase_						:      Optional[str]       =None
      UpperCAmelCase_						:      Optional[str]       =None
      UpperCAmelCase_						:      Optional[int]       =None
      UpperCAmelCase_						:      Optional[str]       ="static"
      UpperCAmelCase_						:      Optional[bool]       =False
      UpperCAmelCase_						:      str       ="main"

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

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

      # args for dynamo
      UpperCAmelCase_						:      dict       =None







      def 						UpperCAmelCase		( self   )       ->   Tuple:






        '''simple docstring'''






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




@dataclass
class 				_lowerCamelCase (    a    ):



      """simple docstring"""






      UpperCAmelCase_						:      str
      UpperCAmelCase_						:      str
      UpperCAmelCase_						:      Optional[str]       =None
      UpperCAmelCase_						:      Optional[str]       =None
      UpperCAmelCase_						:      str       ="us-east-1"
      UpperCAmelCase_						:      int       =1
      UpperCAmelCase_						:      str       ="all"
      UpperCAmelCase_						:      str       =F"""accelerate-sagemaker-{num_machines}"""
      UpperCAmelCase_						:      str       =SAGEMAKER_PYTORCH_VERSION
      UpperCAmelCase_						:      str       =SAGEMAKER_TRANSFORMERS_VERSION
      UpperCAmelCase_						:      str       =SAGEMAKER_PYTHON_VERSION
      UpperCAmelCase_						:      str       =None
      UpperCAmelCase_						:      str       =None
      UpperCAmelCase_						:      dict       =None
      UpperCAmelCase_						:      dict       =None








from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


_UpperCamelCase       = {'''configuration_nat''': ['''NAT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''NatConfig''']}


try:
     if not is_torch_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     _UpperCamelCase       = [
         '''NAT_PRETRAINED_MODEL_ARCHIVE_LIST''',
         '''NatForImageClassification''',
         '''NatModel''',
         '''NatPreTrainedModel''',
         '''NatBackbone''',
     ]

if TYPE_CHECKING:
     from .configuration_nat import NAT_PRETRAINED_CONFIG_ARCHIVE_MAP, NatConfig

     try:
          if not is_torch_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_nat import (
              NAT_PRETRAINED_MODEL_ARCHIVE_LIST,
              NatBackbone,
              NatForImageClassification,
              NatModel,
              NatPreTrainedModel,
          )

else:
     import sys

     _UpperCamelCase       = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)

