




'''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			     =					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 					SCREAMING_SNAKE_CASE(   __lowercase	)			-> Optional[int]:
     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:
          A:		List[str]          =		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
               ):
                    A:		Tuple          =		ClusterConfig
               else:
                    A:		int          =		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
               ):
                    A:		List[Any]          =		ClusterConfig
               else:
                    A:		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 					_snake_case     ( self				:							str	)			->		Dict:







       '''simple docstring'''



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



  @classmethod
  def 					_snake_case     ( cls				:							Any					,  SCREAMING_SNAKE_CASE_				:							Any=None	)			->		str:







       '''simple docstring'''



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



  def 					_snake_case     ( self				:							str					,  SCREAMING_SNAKE_CASE_				:							List[Any]	)			->		int:







       '''simple docstring'''



       with open(SCREAMING_SNAKE_CASE_					,  '''w'''					,  encoding='''utf-8'''	) as f:
            A:		Union[str, Any]          =		json.dumps(self.to_dict()					,  indent=2					,  sort_keys=SCREAMING_SNAKE_CASE_	) + '''\n'''
            f.write(SCREAMING_SNAKE_CASE_	)



  @classmethod
  def 					_snake_case     ( cls				:							List[str]					,  SCREAMING_SNAKE_CASE_				:							Dict=None	)			->		Any:







       '''simple docstring'''



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

       if "mixed_precision" not in config_dict:
            A:		List[Any]          =		'''fp16''' if ('''fp16''' in config_dict and config_dict['''fp16''']) else None
       if isinstance(config_dict['''mixed_precision''']					,  SCREAMING_SNAKE_CASE_	) and not config_dict["mixed_precision"]:
            A:		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.
            A:		List[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:		Any          =		False
       return cls(**SCREAMING_SNAKE_CASE_	)



  def 					_snake_case     ( self				:							List[Any]					,  SCREAMING_SNAKE_CASE_				:							Any	)			->		Union[str, Any]:







       '''simple docstring'''



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




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







       '''simple docstring'''



       if isinstance(self.compute_environment					,  SCREAMING_SNAKE_CASE_	):
            A:		str          =		ComputeEnvironment(self.compute_environment	)
       if isinstance(self.distributed_type					,  SCREAMING_SNAKE_CASE_	):
            if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
                 A:		str          =		SageMakerDistributedType(self.distributed_type	)
            else:
                 A:		List[str]          =		DistributedType(self.distributed_type	)
       if self.dynamo_config is None:
            A:		List[str]          =		{}






@dataclass
class 						lowerCAmelCase_	(       UpperCAmelCase_							):







  '''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 					_snake_case     ( self				:							List[Any]	)			->		List[Any]:







       '''simple docstring'''



       if self.deepspeed_config is None:
            A:		int          =		{}
       if self.fsdp_config is None:
            A:		Optional[int]          =		{}
       if self.megatron_lm_config is None:
            A:		Optional[int]          =		{}
       if self.ipex_config is None:
            A:		str          =		{}
       return super().__post_init__()






@dataclass
class 						lowerCAmelCase_	(       UpperCAmelCase_							):







  '''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












'''simple docstring'''


def 					SCREAMING_SNAKE_CASE(   __lowercase	)			-> int:
     if not isinstance(__lowercase		,				__lowercase	):
          raise ValueError('''double_factorial() only accepts integral values'''	)
     if n < 0:
          raise ValueError('''double_factorial() not defined for negative values'''	)
     return 1 if n <= 1 else n * double_factorial(n - 2	)


if __name__ == "__main__":
     import doctest

     doctest.testmod()






