


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


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






def 						lowercase				(	_snake_case		: Union[str, Any]	)	->str:
	"""simple docstring"""





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



@dataclass
class      _UpperCAmelCase					:






		'''simple docstring'''

		lowerCamelCase__           =42
		lowerCamelCase__           =42
		lowerCamelCase__           =42
		lowerCamelCase__           =42



		def 							SCREAMING_SNAKE_CASE    (self   ):





			'''simple docstring'''

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



		@classmethod
		def 							SCREAMING_SNAKE_CASE    (cls							,			a_=None   ):





			'''simple docstring'''

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



		def 							SCREAMING_SNAKE_CASE    (self							,			a_   ):





			'''simple docstring'''

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



		@classmethod
		def 							SCREAMING_SNAKE_CASE    (cls							,			a_=None   ):





			'''simple docstring'''

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



		def 							SCREAMING_SNAKE_CASE    (self							,			a_   ):





			'''simple docstring'''

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



		def 							SCREAMING_SNAKE_CASE    (self   ):





			'''simple docstring'''

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



@dataclass
class      _UpperCAmelCase					(				__snake_case							):






		'''simple docstring'''

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

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

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

		# args for dynamo
		lowerCamelCase__           =None



		def 							SCREAMING_SNAKE_CASE    (self   ):





			'''simple docstring'''

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



@dataclass
class      _UpperCAmelCase					(				__snake_case							):






		'''simple docstring'''

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









"""simple docstring"""
SCREAMING_SNAKE_CASE					:       List[Any]							   =							1000






def 						lowercase				(	_snake_case		: float	)	->float:
	"""simple docstring"""





	return x * x






def 						lowercase				(	_snake_case		: Union[str, Any]	,  _snake_case		: float	,  _snake_case		: float	,  _snake_case		: int = 4	)	->float:
	"""simple docstring"""





	assert callable(
	    _snake_case	), f"""the function(object) passed should be callable your input : {function}"""
	assert isinstance(_snake_case	,  (float, int)	), f"""a should be float or integer your input : {a}"""
	assert isinstance(function(_snake_case	)	,  (float, int)	), (
	    "the function should return integer or float return type of your function, "
	    f"""{type(_snake_case	)}"""
	)
	assert isinstance(_snake_case	,  (float, int)	), f"""b should be float or integer your input : {b}"""
	assert (
	    isinstance(_snake_case	,  _snake_case	) and precision > 0
	), f"""precision should be positive integer your input : {precision}"""

	# just applying the formula of simpson for approximate integration written in
	# mentioned article in first comment of this file and above this function

	__snake_case      :		Tuple         =							(b - a) / N_STEPS
	__snake_case      :		Union[str, Any]         =							function(_snake_case	) + function(_snake_case	)

	for i in range(1	,  _snake_case	):
		__snake_case      :		List[str]         =							a + h * i
		result += function(_snake_case	) * (4 if i % 2 else 2)

	result *= h / 3
	return round(_snake_case	,  _snake_case	)


if __name__ == "__main__":
			import doctest

			doctest.testmod()





