





# 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


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







def  A					(				UpperCAmelCase					):
					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:
										_snake_case							:       List[Any]												= 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
															):
																				_snake_case							:       Optional[Any]												= ClusterConfig
															else:
																				_snake_case							:       Union[str, Any]												= 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
															):
																				_snake_case							:       Optional[int]												= ClusterConfig
															else:
																				_snake_case							:       List[Any]												= SageMakerConfig
															return config_class.from_yaml_file(yaml_file=lowercase__					)






@dataclass
class 							_a:
		lowerCamelCase__  :ComputeEnvironment
		lowerCamelCase__  :Union[DistributedType, SageMakerDistributedType]
		lowerCamelCase__  :str
		lowerCamelCase__  :bool







		def 							lowercase							(     self					)   ->   List[Any]:


							'''simple docstring'''

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







		@classmethod
		def 							lowercase							(     cls			,    __snake_case=None					)   ->   Union[str, Any]:


							'''simple docstring'''

							_snake_case							:       Tuple												= default_json_config_file if json_file is None else json_file
							with open(__snake_case			,    "r"			,    encoding="utf-8"					) as f:
												_snake_case							:       Optional[int]												= json.load(__snake_case					)
							if "compute_environment" not in config_dict:
												_snake_case							:       Optional[int]												= ComputeEnvironment.LOCAL_MACHINE
							if "mixed_precision" not in config_dict:
												_snake_case							:       Tuple												= "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[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							:       Optional[int]												= False
							return cls(**__snake_case					)







		def 							lowercase							(     self			,    __snake_case					)   ->   Any:


							'''simple docstring'''

							with open(__snake_case			,    "w"			,    encoding="utf-8"					) as f:
												_snake_case							:       List[Any]												= json.dumps(self.to_dict()			,    indent=2			,    sort_keys=__snake_case					) + "\n"
												f.write(__snake_case					)







		@classmethod
		def 							lowercase							(     cls			,    __snake_case=None					)   ->   Union[str, Any]:


							'''simple docstring'''

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

							if "mixed_precision" not in config_dict:
												_snake_case							:       Union[str, Any]												= "fp16" if ("fp16" in config_dict and config_dict["fp16"]) else None
							if isinstance(config_dict["mixed_precision"]			,    __snake_case					) and not config_dict["mixed_precision"]:
												_snake_case							:       Optional[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							:       Optional[Any]												= config_dict.pop("dynamo_backend"					)
												_snake_case							:       Dict												= {} if dynamo_backend == "NO" else {"dynamo_backend": dynamo_backend}
							if "use_cpu" not in config_dict:
												_snake_case							:       List[Any]												= False
							return cls(**__snake_case					)







		def 							lowercase							(     self			,    __snake_case					)   ->   Tuple:


							'''simple docstring'''

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







		def 							lowercase							(     self					)   ->   Optional[int]:


							'''simple docstring'''

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






@dataclass
class 							_a(     _UpperCAmelCase     ):
		lowerCamelCase__  :int
		lowerCamelCase__  :int 					=		0
		lowerCamelCase__  :int 					=		1
		lowerCamelCase__  :Optional[str] 					=		None
		lowerCamelCase__  :Optional[str] 					=		None
		lowerCamelCase__  :Optional[int] 					=		None
		lowerCamelCase__  :Optional[str] 					=		"static"
		lowerCamelCase__  :Optional[bool] 					=		False
		lowerCamelCase__  :str 					=		"main"

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

		# args for TPU pods
		lowerCamelCase__  :str 					=		None
		lowerCamelCase__  :str 					=		None
		lowerCamelCase__  :bool 					=		False
		lowerCamelCase__  :bool 					=		False
		lowerCamelCase__  :str 					=		None
		lowerCamelCase__  :List[str] 					=		None
		lowerCamelCase__  :List[str] 					=		None
		lowerCamelCase__  :List[str] 					=		None

		# args for dynamo
		lowerCamelCase__  :dict 					=		None







		def 							lowercase							(     self					)   ->   int:


							'''simple docstring'''

							if self.deepspeed_config is None:
												_snake_case							:       List[str]												= {}
							if self.fsdp_config is None:
												_snake_case							:       Any												= {}
							if self.megatron_lm_config is None:
												_snake_case							:       Dict												= {}
							if self.ipex_config is None:
												_snake_case							:       Union[str, Any]												= {}
							return super().__post_init__()






@dataclass
class 							_a(     _UpperCAmelCase     ):
		lowerCamelCase__  :str
		lowerCamelCase__  :str
		lowerCamelCase__  :Optional[str] 					=		None
		lowerCamelCase__  :Optional[str] 					=		None
		lowerCamelCase__  :str 					=		"us-east-1"
		lowerCamelCase__  :int 					=		1
		lowerCamelCase__  :str 					=		"all"
		lowerCamelCase__  :str 					=		f'accelerate-sagemaker-{num_machines}'
		lowerCamelCase__  :str 					=		SAGEMAKER_PYTORCH_VERSION
		lowerCamelCase__  :str 					=		SAGEMAKER_TRANSFORMERS_VERSION
		lowerCamelCase__  :str 					=		SAGEMAKER_PYTHON_VERSION
		lowerCamelCase__  :str 					=		None
		lowerCamelCase__  :str 					=		None
		lowerCamelCase__  :dict 					=		None
		lowerCamelCase__  :dict 					=		None




from __future__ import annotations

from typing import Generic, TypeVar

UpperCamelCase__			=    TypeVar("T")
class       _lowerCAmelCase (			Generic[T]      ):






			"""simple docstring"""





			def __init__(					self						:							int      ,  lowercase						:							T )    ->       Union[str, Any]:
									"""simple docstring"""







									__lowercase											=					data  # Assign data
									__lowercase											=					None  # Initialize next as null
									__lowercase											=					None  # Initialize prev as null





class       _lowerCAmelCase (			Generic[T]      ):






			"""simple docstring"""





			def __init__(					self						:							Any )    ->       None:
									"""simple docstring"""







									__lowercase											=					None





			def 		snake_case__      (					self						:							str      ,  lowercase						:							T )    ->       None:
									"""simple docstring"""







									if self.head is None:
															__lowercase											=					Node(lowercase )
									else:
															__lowercase											=					Node(lowercase )
															__lowercase											=					new_node
															__lowercase											=					self.head
															__lowercase											=					None
															__lowercase											=					new_node





			def 		snake_case__      (					self						:							Optional[Any] )    ->       T | None:
									"""simple docstring"""







									if self.head is None:
															return None
									else:
															assert self.head is not None
															__lowercase											=					self.head.data
															__lowercase											=					self.head.next
															if self.head is not None:
																					__lowercase											=					None
															return temp





			def 		snake_case__      (					self						:							Optional[Any] )    ->       T | None:
									"""simple docstring"""







									return self.head.data if self.head is not None else None





			def __len__(					self						:							List[str] )    ->       int:
									"""simple docstring"""







									__lowercase											=					self.head
									__lowercase											=					0
									while temp is not None:
															count += 1
															__lowercase											=					temp.next
									return count





			def 		snake_case__      (					self						:							Optional[Any] )    ->       bool:
									"""simple docstring"""







									return self.head is None







			def 		snake_case__      (					self						:							Optional[Any] )    ->       None:
									"""simple docstring"""







									print("""stack elements are:""" )
									__lowercase											=					self.head
									while temp is not None:
															print(temp.data      ,  end="""->""" )
															__lowercase											=					temp.next


# Code execution starts here
if __name__ == "__main__":
			# Start with the empty stack
			UpperCamelCase__			=    Stack()

			# Insert 4 at the beginning. So stack becomes 4->None
			print("Stack operations using Doubly LinkedList")
			stack.push(4)

			# Insert 5 at the beginning. So stack becomes 4->5->None
			stack.push(5)

			# Insert 6 at the beginning. So stack becomes 4->5->6->None
			stack.push(6)

			# Insert 7 at the beginning. So stack becomes 4->5->6->7->None
			stack.push(7)

			# Print the stack
			stack.print_stack()

			# Print the top element
			print("\nTop element is ", stack.top())

			# Print the stack size
			print("Size of the stack is ", len(stack))

			# pop the top element
			stack.pop()

			# pop the top element
			stack.pop()

			# two elements have now been popped off
			stack.print_stack()

			# Print True if the stack is empty else False
			print("\nstack is empty:", stack.is_empty())





