
'''simple docstring'''



# 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__					:						List[Any]											=     os.path.expanduser(
    os.getenv("HF_HOME", os.path.join(os.getenv("XDG_CACHE_HOME", "~/.cache"), "huggingface"))
)
UpperCamelCase__					:						str											=     os.path.join(hf_cache_home, "accelerate")
UpperCamelCase__					:						str											=     os.path.join(cache_dir, "default_config.yaml")
UpperCamelCase__					:						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__					:						Any											=     default_yaml_config_file
else:
     UpperCamelCase__					:						int											=     default_json_config_file
def       lowerCAmelCase_		( SCREAMING_SNAKE_CASE_  )   ->   int:




   """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:
      _SCREAMING_SNAKE_CASE          = 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
         ):
            _SCREAMING_SNAKE_CASE          = ClusterConfig
         else:
            _SCREAMING_SNAKE_CASE          = 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
         ):
            _SCREAMING_SNAKE_CASE          = ClusterConfig
         else:
            _SCREAMING_SNAKE_CASE          = SageMakerConfig
         return config_class.from_yaml_file(yaml_file=SCREAMING_SNAKE_CASE_  )

@dataclass
class       _a :





       """simple docstring"""




       SCREAMING_SNAKE_CASE					=     42
       SCREAMING_SNAKE_CASE					=     42
       SCREAMING_SNAKE_CASE					=     42
       SCREAMING_SNAKE_CASE					=     42






       def 				UpperCamelCase (							self					)			->	Optional[Any]:
          _SCREAMING_SNAKE_CASE          = 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__					):
                _SCREAMING_SNAKE_CASE          = value.value
             if isinstance(A__				,							A__					) and not bool(A__					):
                _SCREAMING_SNAKE_CASE          = None
          _SCREAMING_SNAKE_CASE          = {k: v for k, v in result.items() if v is not None}
          return result






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






       def 				UpperCamelCase (							self				,							A__					)			->	List[str]:
          with open(A__				,							"""w"""				,							encoding="""utf-8"""					) as f:
             _SCREAMING_SNAKE_CASE          = json.dumps(self.to_dict()				,							indent=2				,							sort_keys=A__					) + """\n"""
             f.write(A__					)






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

          if "mixed_precision" not in config_dict:
             _SCREAMING_SNAKE_CASE          = """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"]:
             _SCREAMING_SNAKE_CASE          = """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.
             _SCREAMING_SNAKE_CASE          = config_dict.pop("""dynamo_backend"""					)
             _SCREAMING_SNAKE_CASE          = {} if dynamo_backend == """NO""" else {"""dynamo_backend""": dynamo_backend}
          if "use_cpu" not in config_dict:
             _SCREAMING_SNAKE_CASE          = False
          return cls(**A__					)






       def 				UpperCamelCase (							self				,							A__					)			->	List[Any]:
          with open(A__				,							"""w"""				,							encoding="""utf-8"""					) as f:
             yaml.safe_dump(self.to_dict()				,							A__					)






       def 				UpperCamelCase (							self					)			->	Optional[Any]:
          if isinstance(self.compute_environment				,							A__					):
             _SCREAMING_SNAKE_CASE          = ComputeEnvironment(self.compute_environment					)
          if isinstance(self.distributed_type				,							A__					):
             if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
                _SCREAMING_SNAKE_CASE          = SageMakerDistributedType(self.distributed_type					)
             else:
                _SCREAMING_SNAKE_CASE          = DistributedType(self.distributed_type					)
          if self.dynamo_config is None:
             _SCREAMING_SNAKE_CASE          = {}






@dataclass
class       _a (_lowerCamelCase):





       """simple docstring"""




       SCREAMING_SNAKE_CASE					=     42
       SCREAMING_SNAKE_CASE					=     0
       SCREAMING_SNAKE_CASE					=     1
       SCREAMING_SNAKE_CASE					=     None
       SCREAMING_SNAKE_CASE					=     None
       SCREAMING_SNAKE_CASE					=     None
       SCREAMING_SNAKE_CASE					=     "static"
       SCREAMING_SNAKE_CASE					=     False
       SCREAMING_SNAKE_CASE					=     "main"

       # args for deepspeed_plugin
       SCREAMING_SNAKE_CASE					=     None
       # args for fsdp
       SCREAMING_SNAKE_CASE					=     None
       # args for megatron_lm
       SCREAMING_SNAKE_CASE					=     None
       # args for ipex
       SCREAMING_SNAKE_CASE					=     None
       # args for TPU
       SCREAMING_SNAKE_CASE					=     False

       # args for TPU pods
       SCREAMING_SNAKE_CASE					=     None
       SCREAMING_SNAKE_CASE					=     None
       SCREAMING_SNAKE_CASE					=     False
       SCREAMING_SNAKE_CASE					=     False
       SCREAMING_SNAKE_CASE					=     None
       SCREAMING_SNAKE_CASE					=     None
       SCREAMING_SNAKE_CASE					=     None
       SCREAMING_SNAKE_CASE					=     None

       # args for dynamo
       SCREAMING_SNAKE_CASE					=     None






       def 				UpperCamelCase (							self					)			->	Dict:
          if self.deepspeed_config is None:
             _SCREAMING_SNAKE_CASE          = {}
          if self.fsdp_config is None:
             _SCREAMING_SNAKE_CASE          = {}
          if self.megatron_lm_config is None:
             _SCREAMING_SNAKE_CASE          = {}
          if self.ipex_config is None:
             _SCREAMING_SNAKE_CASE          = {}
          return super().__post_init__()






@dataclass
class       _a (_lowerCamelCase):





       """simple docstring"""




       SCREAMING_SNAKE_CASE					=     42
       SCREAMING_SNAKE_CASE					=     42
       SCREAMING_SNAKE_CASE					=     None
       SCREAMING_SNAKE_CASE					=     None
       SCREAMING_SNAKE_CASE					=     "us-east-1"
       SCREAMING_SNAKE_CASE					=     1
       SCREAMING_SNAKE_CASE					=     "all"
       SCREAMING_SNAKE_CASE					=     f'''accelerate-sagemaker-{num_machines}'''
       SCREAMING_SNAKE_CASE					=     SAGEMAKER_PYTORCH_VERSION
       SCREAMING_SNAKE_CASE					=     SAGEMAKER_TRANSFORMERS_VERSION
       SCREAMING_SNAKE_CASE					=     SAGEMAKER_PYTHON_VERSION
       SCREAMING_SNAKE_CASE					=     None
       SCREAMING_SNAKE_CASE					=     None
       SCREAMING_SNAKE_CASE					=     None
       SCREAMING_SNAKE_CASE					=     None








'''simple docstring'''



from ..utils import DummyObject, requires_backends

class       _a (metaclass=_lowerCamelCase):





       """simple docstring"""




       SCREAMING_SNAKE_CASE					=     ['torch', 'librosa']






       def __init__(							self				,							*A__				,							**A__					)			->	str:
          requires_backends(self				,							["""torch""", """librosa"""]					)






       @classmethod
       def 				UpperCamelCase (							cls				,							*A__				,							**A__					)			->	Tuple:
          requires_backends(cls				,							["""torch""", """librosa"""]					)






       @classmethod
       def 				UpperCamelCase (							cls				,							*A__				,							**A__					)			->	Optional[Any]:
          requires_backends(cls				,							["""torch""", """librosa"""]					)






class       _a (metaclass=_lowerCamelCase):





       """simple docstring"""




       SCREAMING_SNAKE_CASE					=     ['torch', 'librosa']






       def __init__(							self				,							*A__				,							**A__					)			->	Dict:
          requires_backends(self				,							["""torch""", """librosa"""]					)






       @classmethod
       def 				UpperCamelCase (							cls				,							*A__				,							**A__					)			->	Optional[Any]:
          requires_backends(cls				,							["""torch""", """librosa"""]					)






       @classmethod
       def 				UpperCamelCase (							cls				,							*A__				,							**A__					)			->	Union[str, Any]:
          requires_backends(cls				,							["""torch""", """librosa"""]					)






