


# 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


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


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







@dataclass
class     __A:
				snake_case_		     =					42
				snake_case_		     =					42
				snake_case_		     =					42
				snake_case_		     =					42




				def        SCREAMING_SNAKE_CASE_	(  self       )					->   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(_snake_case	,  _snake_case       ):
																__a    							=					value.value
												if isinstance(_snake_case	,  _snake_case       ) and not bool(_snake_case       ):
																__a    							=					None
								__a    							=					{k: v for k, v in result.items() if v is not None}
								return result




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


								'''simple docstring'''




								__a    							=					default_json_config_file if json_file is None else json_file
								with open(_snake_case	,  '''r'''	,  encoding='''utf-8'''       ) as f:
												__a    							=					json.load(_snake_case       )
								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(**_snake_case       )




				def        SCREAMING_SNAKE_CASE_	(  self	,  _snake_case       )					->   int:


								'''simple docstring'''




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




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


								'''simple docstring'''




								__a    							=					default_yaml_config_file if yaml_file is None else yaml_file
								with open(_snake_case	,  '''r'''	,  encoding='''utf-8'''       ) as f:
												__a    							=					yaml.safe_load(_snake_case       )
								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''']	,  _snake_case       ) 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(**_snake_case       )




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


								'''simple docstring'''




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




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


								'''simple docstring'''




								if isinstance(self.compute_environment	,  _snake_case       ):
												__a    							=					ComputeEnvironment(self.compute_environment       )
								if isinstance(self.distributed_type	,  _snake_case       ):
												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    ):
				snake_case_		     =					42
				snake_case_		     =					0
				snake_case_		     =					1
				snake_case_		     =					None
				snake_case_		     =					None
				snake_case_		     =					None
				snake_case_		     =					"static"
				snake_case_		     =					False
				snake_case_		     =					"main"

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

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

				# args for dynamo
				snake_case_		     =					None




				def        SCREAMING_SNAKE_CASE_	(  self       )					->   Tuple:


								'''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    ):
				snake_case_		     =					42
				snake_case_		     =					42
				snake_case_		     =					None
				snake_case_		     =					None
				snake_case_		     =					"us-east-1"
				snake_case_		     =					1
				snake_case_		     =					"all"
				snake_case_		     =					f"""accelerate-sagemaker-{num_machines}"""
				snake_case_		     =					SAGEMAKER_PYTORCH_VERSION
				snake_case_		     =					SAGEMAKER_TRANSFORMERS_VERSION
				snake_case_		     =					SAGEMAKER_PYTHON_VERSION
				snake_case_		     =					None
				snake_case_		     =					None
				snake_case_		     =					None
				snake_case_		     =					None

import math
from collections import OrderedDict

import torch
from packaging import version
from torch import Tensor, nn

from .utils import logging


A  :			List[str]     				=				logging.get_logger(__name__)







class     __A(				nn.Module    ):




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


								'''simple docstring'''




								super().__init__()
								if version.parse(torch.__version__       ) < version.parse('''1.12.0'''       ):
												raise ImportError(
												    F"""You are using torch=={torch.__version__}, but torch>=1.12.0 is required to use """
												    '''PytorchGELUTanh. Please upgrade torch.'''       )




				def        SCREAMING_SNAKE_CASE_	(  self	,  _snake_case       )					->   Tensor:


								'''simple docstring'''




								return nn.functional.gelu(_snake_case	,  approximate='''tanh'''       )







class     __A(				nn.Module    ):




				def        SCREAMING_SNAKE_CASE_	(  self	,  _snake_case       )					->   Tensor:


								'''simple docstring'''




								return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi       ) * (input + 0.04_4715 * torch.pow(_snake_case	,  3.0       ))       ))







class     __A(				nn.Module    ):




				def __init__(  self	,  _snake_case = False       )					->   Tuple:


								'''simple docstring'''




								super().__init__()
								if use_gelu_python:
												__a    							=					self._gelu_python
								else:
												__a    							=					nn.functional.gelu




				def        SCREAMING_SNAKE_CASE_	(  self	,  _snake_case       )					->   Tensor:


								'''simple docstring'''




								return input * 0.5 * (1.0 + torch.erf(input / math.sqrt(2.0       )       ))




				def        SCREAMING_SNAKE_CASE_	(  self	,  _snake_case       )					->   Tensor:


								'''simple docstring'''




								return self.act(_snake_case       )







class     __A(				nn.Module    ):




				def        SCREAMING_SNAKE_CASE_	(  self	,  _snake_case       )					->   Tensor:


								'''simple docstring'''




								return 0.5 * input * (1.0 + torch.tanh(input * 0.79_7884_5608 * (1.0 + 0.04_4715 * input * input)       ))







class     __A(				nn.Module    ):




				def        SCREAMING_SNAKE_CASE_	(  self	,  _snake_case       )					->   Tensor:


								'''simple docstring'''




								return input * torch.sigmoid(1.702 * input       )







class     __A(				nn.Module    ):




				def __init__(  self	,  _snake_case	,  _snake_case       )					->   Optional[int]:


								'''simple docstring'''




								if min > max:
												raise ValueError(F"""min should be < max (got min: {min}, max: {max})"""       )

								super().__init__()
								__a    							=					min
								__a    							=					max




				def        SCREAMING_SNAKE_CASE_	(  self	,  _snake_case       )					->   Tensor:


								'''simple docstring'''




								return torch.clip(gelu(_snake_case       )	,  self.min	,  self.max       )







class     __A(				nn.Module    ):




				def __init__(  self       )					->   str:


								'''simple docstring'''




								super().__init__()
								__a    							=					math.sqrt(2 / math.pi       )




				def        SCREAMING_SNAKE_CASE_	(  self	,  _snake_case       )					->   Tensor:


								'''simple docstring'''




								return 0.5 * input * (1 + torch.tanh(self.precomputed_constant * (input + 0.04_4715 * torch.pow(_snake_case	,  3       ))       ))







class     __A(				nn.Module    ):




				def        SCREAMING_SNAKE_CASE_	(  self	,  _snake_case       )					->   Tensor:


								'''simple docstring'''




								return nn.functional.silu(_snake_case       )







class     __A(				nn.Module    ):




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


								'''simple docstring'''




								super().__init__()
								if version.parse(torch.__version__       ) < version.parse('''1.9.0'''       ):
												__a    							=					self._mish_python
								else:
												__a    							=					nn.functional.mish




				def        SCREAMING_SNAKE_CASE_	(  self	,  _snake_case       )					->   Tensor:


								'''simple docstring'''




								return input * torch.tanh(nn.functional.softplus(_snake_case       )       )




				def        SCREAMING_SNAKE_CASE_	(  self	,  _snake_case       )					->   Tensor:


								'''simple docstring'''




								return self.act(_snake_case       )







class     __A(				nn.Module    ):




				def        SCREAMING_SNAKE_CASE_	(  self	,  _snake_case       )					->   Tensor:


								'''simple docstring'''




								return input







class     __A(				nn.Module    ):




				def        SCREAMING_SNAKE_CASE_	(  self	,  _snake_case	,  _snake_case=0.70_7107	,  _snake_case=0.28_2095       )					->   int:


								'''simple docstring'''




								__a    							=					(input - mu).div(sigma * math.sqrt(2.0       )       )
								return 0.5 * (1.0 + torch.erf(_snake_case       ))







class     __A(				nn.Module    ):




				def        SCREAMING_SNAKE_CASE_	(  self	,  _snake_case       )					->   Any:


								'''simple docstring'''




								__a    							=					nn.functional.relu(_snake_case       )
								__a    							=					torch.square(_snake_case       )
								return squared







class     __A(				a    ):




				def __getitem__(  self	,  _snake_case       )					->   Dict:


								'''simple docstring'''




								__a    							=					super().__getitem__(_snake_case       )
								__a							,  __a    							=					content if isinstance(_snake_case	,  _snake_case       ) else (content, {})
								return cls(**_snake_case       )



A  :			str     				=				{
    'gelu': GELUActivation,
    'gelu_10': (ClippedGELUActivation, {'min': -1_0, 'max': 1_0}),
    'gelu_fast': FastGELUActivation,
    'gelu_new': NewGELUActivation,
    'gelu_python': (GELUActivation, {'use_gelu_python': True}),
    'gelu_pytorch_tanh': PytorchGELUTanh,
    'gelu_accurate': AccurateGELUActivation,
    'laplace': LaplaceActivation,
    'linear': LinearActivation,
    'mish': MishActivation,
    'quick_gelu': QuickGELUActivation,
    'relu': nn.ReLU,
    'relu2': ReLUSquaredActivation,
    'relu6': nn.ReLUa,
    'sigmoid': nn.Sigmoid,
    'silu': SiLUActivation,
    'swish': SiLUActivation,
    'tanh': nn.Tanh,
}
A  :			Any     				=				ClassInstantier(ACTaCLS)


def 					__lowerCAmelCase    (    a__						) ->						Optional[int]:
				if activation_string in ACTaFN:
								return ACTaFN[activation_string]
				else:
								raise KeyError(F"""function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys()						)}"""						)


# For backwards compatibility with: from activations import gelu_python
A  :			Optional[Any]     				=				get_activation('gelu_python')
A  :			str     				=				get_activation('gelu_new')
A  :			Any     				=				get_activation('gelu')
A  :			int     				=				get_activation('gelu_fast')
A  :			Any     				=				get_activation('quick_gelu')
A  :			int     				=				get_activation('silu')
A  :			List[str]     				=				get_activation('mish')






A  :			Dict     				=				get_activation('linear')