




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


_snake_case      :      int   							=		os.path.expanduser(
    os.getenv('HF_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'huggingface'))
)
_snake_case      :      Tuple   							=		os.path.join(hf_cache_home, 'accelerate')
_snake_case      :      List[str]   							=		os.path.join(cache_dir, 'default_config.yaml')
_snake_case      :      Any   							=		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):
				_snake_case      :      str   							=		default_yaml_config_file
else:
				_snake_case      :      Union[str, Any]   							=		default_json_config_file
def 		snake_case_    (UpperCamelCase       :  List[Any]      ):





							'''simple docstring'''


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

@dataclass
class 			A    :
							lowercase_							=				42
							lowercase_							=				42
							lowercase_							=				42
							lowercase_							=				42







							def    __lowerCAmelCase			(  self       :  Optional[Any]					)			->							Optional[int]:


														"""simple docstring"""


														_a	     =				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_					):
																												_a	     =				value.value
																					if isinstance(lowerCAmelCase_							,			lowerCAmelCase_					) and not bool(lowerCAmelCase_					):
																												_a	     =				None
														_a	     =				{k: v for k, v in result.items() if v is not None}
														return result







							@classmethod
							def    __lowerCAmelCase			(  cls       :  Optional[Any]							,			lowerCAmelCase_       :  Tuple=None					)			->							Optional[int]:


														"""simple docstring"""


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







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


														"""simple docstring"""


														with open(lowerCAmelCase_							,			'''w'''							,			encoding='''utf-8'''					) as f:
																					_a	     =				json.dumps(self.to_dict()							,			indent=2							,			sort_keys=lowerCAmelCase_					) + '''\n'''
																					f.write(lowerCAmelCase_					)







							@classmethod
							def    __lowerCAmelCase			(  cls       :  int							,			lowerCAmelCase_       :  Optional[int]=None					)			->							Optional[int]:


														"""simple docstring"""


														_a	     =				default_yaml_config_file if yaml_file is None else yaml_file
														with open(lowerCAmelCase_							,			'''r'''							,			encoding='''utf-8'''					) as f:
																					_a	     =				yaml.safe_load(lowerCAmelCase_					)
														if "compute_environment" not in config_dict:
																					_a	     =				ComputeEnvironment.LOCAL_MACHINE

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







							def    __lowerCAmelCase			(  self       :  List[str]							,			lowerCAmelCase_       :  List[Any]					)			->							int:


														"""simple docstring"""


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







							def    __lowerCAmelCase			(  self       :  int					)			->							Tuple:


														"""simple docstring"""


														if isinstance(self.compute_environment							,			lowerCAmelCase_					):
																					_a	     =				ComputeEnvironment(self.compute_environment					)
														if isinstance(self.distributed_type							,			lowerCAmelCase_					):
																					if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
																												_a	     =				SageMakerDistributedType(self.distributed_type					)
																					else:
																												_a	     =				DistributedType(self.distributed_type					)
														if self.dynamo_config is None:
																					_a	     =				{}



@dataclass
class 			A    (		_a    ):
							lowercase_							=				42
							lowercase_							=				0
							lowercase_							=				1
							lowercase_							=				None
							lowercase_							=				None
							lowercase_							=				None
							lowercase_							=				"static"
							lowercase_							=				False
							lowercase_							=				"main"

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

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

							# args for dynamo
							lowercase_							=				None







							def    __lowerCAmelCase			(  self       :  Optional[int]					)			->							Dict:


														"""simple docstring"""


														if self.deepspeed_config is None:
																					_a	     =				{}
														if self.fsdp_config is None:
																					_a	     =				{}
														if self.megatron_lm_config is None:
																					_a	     =				{}
														if self.ipex_config is None:
																					_a	     =				{}
														return super().__post_init__()



@dataclass
class 			A    (		_a    ):
							lowercase_							=				42
							lowercase_							=				42
							lowercase_							=				None
							lowercase_							=				None
							lowercase_							=				"us-east-1"
							lowercase_							=				1
							lowercase_							=				"all"
							lowercase_							=				f'accelerate-sagemaker-{num_machines}'
							lowercase_							=				SAGEMAKER_PYTORCH_VERSION
							lowercase_							=				SAGEMAKER_TRANSFORMERS_VERSION
							lowercase_							=				SAGEMAKER_PYTHON_VERSION
							lowercase_							=				None
							lowercase_							=				None
							lowercase_							=				None
							lowercase_							=				None







'''simple docstring'''


from __future__ import annotations

from enum import Enum

class 			A    (		_a    ):
							lowercase_							=				24
							lowercase_							=				21
							lowercase_							=				18
							lowercase_							=				15
							lowercase_							=				12
							lowercase_							=				9
							lowercase_							=				6
							lowercase_							=				3
							lowercase_							=				2
							lowercase_							=				1
							lowercase_							=				-1
							lowercase_							=				-2
							lowercase_							=				-3
							lowercase_							=				-6
							lowercase_							=				-9
							lowercase_							=				-12
							lowercase_							=				-15
							lowercase_							=				-18
							lowercase_							=				-21
							lowercase_							=				-24



class 			A    (		_a    ):
							lowercase_							=				8
							lowercase_							=				7
							lowercase_							=				6
							lowercase_							=				5
							lowercase_							=				4
							lowercase_							=				3
							lowercase_							=				2
							lowercase_							=				1



def 		snake_case_    (UpperCamelCase       :  float ,						UpperCamelCase       :  str | SIUnit ,						UpperCamelCase       :  str | SIUnit ,						):





							'''simple docstring'''


							if isinstance(UpperCamelCase ,						UpperCamelCase      ):
														_a	     =				SIUnit[known_prefix.lower()]
							if isinstance(UpperCamelCase ,						UpperCamelCase      ):
														_a	     =				SIUnit[unknown_prefix.lower()]
							_a	     =				known_amount * (
							    10 ** (known_prefix.value - unknown_prefix.value)
							)
							return unknown_amount
def 		snake_case_    (UpperCamelCase       :  float ,						UpperCamelCase       :  str | BinaryUnit ,						UpperCamelCase       :  str | BinaryUnit ,						):





							'''simple docstring'''


							if isinstance(UpperCamelCase ,						UpperCamelCase      ):
														_a	     =				BinaryUnit[known_prefix.lower()]
							if isinstance(UpperCamelCase ,						UpperCamelCase      ):
														_a	     =				BinaryUnit[unknown_prefix.lower()]
							_a	     =				known_amount * (
							    2 ** ((known_prefix.value - unknown_prefix.value) * 10)
							)
							return unknown_amount


if __name__ == "__main__":
				import doctest

				doctest.testmod()

