


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





def 						_lowerCamelCase		(							SCREAMING_SNAKE_CASE_				: Any      ):






							"""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:
														a_       :   str			=	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
																					):
																												a_       :   Union[str, Any]			=	ClusterConfig
																					else:
																												a_       :   Optional[Any]			=	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
																					):
																												a_       :   Optional[Any]			=	ClusterConfig
																					else:
																												a_       :   Any			=	SageMakerConfig
																					return config_class.from_yaml_file(yaml_file=SCREAMING_SNAKE_CASE_      )





@dataclass
class 					snake_case__  :
	UpperCAmelCase   :							ComputeEnvironment
	UpperCAmelCase   :							Union[DistributedType, SageMakerDistributedType]
	UpperCAmelCase   :							str
	UpperCAmelCase   :							bool





	def     A				(  self							)		->			Union[str, Any]:
								"""simple docstring"""






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





	@classmethod
	def     A				(  cls				,    UpperCamelCase_=None							)		->			str:
								"""simple docstring"""






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





	def     A				(  self				,    UpperCamelCase_							)		->			Tuple:
								"""simple docstring"""






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





	@classmethod
	def     A				(  cls				,    UpperCamelCase_=None							)		->			Dict:
								"""simple docstring"""






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

								if "mixed_precision" not in config_dict:
															a_       :   Union[str, 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"]:
															a_       :   Tuple			=	"""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_       :   Tuple			=	config_dict.pop("""dynamo_backend"""							)
															a_       :   str			=	{} if dynamo_backend == """NO""" else {"""dynamo_backend""": dynamo_backend}
								if "use_cpu" not in config_dict:
															a_       :   str			=	False
								return cls(**UpperCamelCase_							)





	def     A				(  self				,    UpperCamelCase_							)		->			Tuple:
								"""simple docstring"""






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





	def     A				(  self							)		->			Dict:
								"""simple docstring"""






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





@dataclass
class 					snake_case__  ( __A       ):
	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     A				(  self							)		->			List[Any]:
								"""simple docstring"""






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





@dataclass
class 					snake_case__  ( __A       ):
	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






def 						_lowerCamelCase		(							SCREAMING_SNAKE_CASE_				: list[int]      ):






							"""simple docstring"""



							a_       :   List[Any]			=	len(SCREAMING_SNAKE_CASE_      )
							if n in (0, 1):
														return 0
							return sum(query * (n - i - 1) for i, query in enumerate(sorted(SCREAMING_SNAKE_CASE_      )      )      )


if __name__ == "__main__":
	import doctest

	doctest.testmod()


