



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



def  lowercase    (				SCREAMING_SNAKE_CASE__    :		Dict			)					->       Optional[Any]:
 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:
  _snake_case      :					List[Any]					=   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
   ):
    _snake_case      :					Any					=   ClusterConfig
   else:
    _snake_case      :					int					=   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
   ):
    _snake_case      :					int					=   ClusterConfig
   else:
    _snake_case      :					Optional[Any]					=   SageMakerConfig
   return config_class.from_yaml_file(yaml_file=SCREAMING_SNAKE_CASE__			)







@dataclass
class 						snake_case  :



   '''simple docstring'''






   snake_case_   :	ComputeEnvironment
   snake_case_   :	Union[DistributedType, SageMakerDistributedType]
   snake_case_   :	str
   snake_case_   :	bool

   def        UpperCamelCase_					(   self							:     Optional[int])			->			str:

    """simple docstring"""







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

   @classmethod
   def        UpperCamelCase_					(   cls							:     Tuple			,						lowerCAmelCase							:     Any=None)			->			str:

    """simple docstring"""







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

   def        UpperCamelCase_					(   self							:     Union[str, Any]			,						lowerCAmelCase							:     Optional[Any])			->			Dict:

    """simple docstring"""







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

   @classmethod
   def        UpperCamelCase_					(   cls							:     Optional[Any]			,						lowerCAmelCase							:     Optional[Any]=None)			->			Union[str, Any]:

    """simple docstring"""







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

    if "mixed_precision" not in config_dict:
     _snake_case      :					Any					=   """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"]:
     _snake_case      :					List[str]					=   """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      :					Dict					=   {} if dynamo_backend == """NO""" else {"""dynamo_backend""": dynamo_backend}
    if "use_cpu" not in config_dict:
     _snake_case      :					Optional[int]					=   False
    return cls(**lowerCAmelCase)

   def        UpperCamelCase_					(   self							:     Dict			,						lowerCAmelCase							:     List[str])			->			List[Any]:

    """simple docstring"""







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


   def        UpperCamelCase_					(   self							:     Tuple)			->			Tuple:

    """simple docstring"""







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







@dataclass
class 						snake_case  (		SCREAMING_SNAKE_CASE_					):



   '''simple docstring'''






   snake_case_   :	int
   snake_case_   :	int       =						0
   snake_case_   :	int       =						1
   snake_case_   :	Optional[str]       =						None
   snake_case_   :	Optional[str]       =						None
   snake_case_   :	Optional[int]       =						None
   snake_case_   :	Optional[str]       =						"static"
   snake_case_   :	Optional[bool]       =						False
   snake_case_   :	str       =						"main"

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

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

   # args for dynamo
   snake_case_   :	dict       =						None

   def        UpperCamelCase_					(   self							:     List[Any])			->			str:

    """simple docstring"""







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







@dataclass
class 						snake_case  (		SCREAMING_SNAKE_CASE_					):



   '''simple docstring'''






   snake_case_   :	str
   snake_case_   :	str
   snake_case_   :	Optional[str]       =						None
   snake_case_   :	Optional[str]       =						None
   snake_case_   :	str       =						"us-east-1"
   snake_case_   :	int       =						1
   snake_case_   :	str       =						"all"
   snake_case_   :	str       =						f'''accelerate-sagemaker-{num_machines}'''
   snake_case_   :	str       =						SAGEMAKER_PYTORCH_VERSION
   snake_case_   :	str       =						SAGEMAKER_TRANSFORMERS_VERSION
   snake_case_   :	str       =						SAGEMAKER_PYTHON_VERSION
   snake_case_   :	str       =						None
   snake_case_   :	str       =						None
   snake_case_   :	dict       =						None
   snake_case_   :	dict       =						None





import math
from collections import OrderedDict

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

from .utils import logging


a__      =		logging.get_logger(__name__)







class 						snake_case  (		nn.Module					):



   '''simple docstring'''






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

    """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        UpperCamelCase_					(   self							:     Tuple			,						lowerCAmelCase							:     Tensor)			->			Tensor:

    """simple docstring"""







    return nn.functional.gelu(lowerCAmelCase			,						approximate="""tanh""")







class 						snake_case  (		nn.Module					):



   '''simple docstring'''






   def        UpperCamelCase_					(   self							:     Optional[int]			,						lowerCAmelCase							:     Tensor)			->			Tensor:

    """simple docstring"""







    return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (input + 0.044_715 * torch.pow(lowerCAmelCase			,						3.0))))







class 						snake_case  (		nn.Module					):



   '''simple docstring'''






   def __init__(   self							:     str			,						lowerCAmelCase							:     bool = False)			->			Optional[Any]:

    """simple docstring"""







    super().__init__()
    if use_gelu_python:
     _snake_case      :					Optional[int]					=   self._gelu_python
    else:
     _snake_case      :					Any					=   nn.functional.gelu

   def        UpperCamelCase_					(   self							:     Union[str, Any]			,						lowerCAmelCase							:     Tensor)			->			Tensor:

    """simple docstring"""







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


   def        UpperCamelCase_					(   self							:     str			,						lowerCAmelCase							:     Tensor)			->			Tensor:

    """simple docstring"""







    return self.act(lowerCAmelCase)







class 						snake_case  (		nn.Module					):



   '''simple docstring'''






   def        UpperCamelCase_					(   self							:     int			,						lowerCAmelCase							:     Tensor)			->			Tensor:

    """simple docstring"""







    return 0.5 * input * (1.0 + torch.tanh(input * 0.7_978_845_608 * (1.0 + 0.044_715 * input * input)))







class 						snake_case  (		nn.Module					):



   '''simple docstring'''






   def        UpperCamelCase_					(   self							:     int			,						lowerCAmelCase							:     Tensor)			->			Tensor:

    """simple docstring"""







    return input * torch.sigmoid(1.702 * input)







class 						snake_case  (		nn.Module					):



   '''simple docstring'''






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

    """simple docstring"""







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

    super().__init__()
    _snake_case      :					Dict					=   min
    _snake_case      :					Optional[int]					=   max


   def        UpperCamelCase_					(   self							:     Union[str, Any]			,						lowerCAmelCase							:     Tensor)			->			Tensor:

    """simple docstring"""







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







class 						snake_case  (		nn.Module					):



   '''simple docstring'''






   def __init__(   self							:     Tuple)			->			List[str]:

    """simple docstring"""







    super().__init__()
    _snake_case      :					Union[str, Any]					=   math.sqrt(2 / math.pi)


   def        UpperCamelCase_					(   self							:     Dict			,						lowerCAmelCase							:     Tensor)			->			Tensor:

    """simple docstring"""







    return 0.5 * input * (1 + torch.tanh(self.precomputed_constant * (input + 0.044_715 * torch.pow(lowerCAmelCase			,						3))))







class 						snake_case  (		nn.Module					):



   '''simple docstring'''






   def        UpperCamelCase_					(   self							:     Dict			,						lowerCAmelCase							:     Tensor)			->			Tensor:

    """simple docstring"""







    return nn.functional.silu(lowerCAmelCase)







class 						snake_case  (		nn.Module					):



   '''simple docstring'''






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

    """simple docstring"""







    super().__init__()
    if version.parse(torch.__version__) < version.parse("""1.9.0"""):
     _snake_case      :					Optional[int]					=   self._mish_python
    else:
     _snake_case      :					List[str]					=   nn.functional.mish

   def        UpperCamelCase_					(   self							:     str			,						lowerCAmelCase							:     Tensor)			->			Tensor:

    """simple docstring"""







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


   def        UpperCamelCase_					(   self							:     str			,						lowerCAmelCase							:     Tensor)			->			Tensor:

    """simple docstring"""







    return self.act(lowerCAmelCase)







class 						snake_case  (		nn.Module					):



   '''simple docstring'''






   def        UpperCamelCase_					(   self							:     Optional[Any]			,						lowerCAmelCase							:     Tensor)			->			Tensor:

    """simple docstring"""







    return input







class 						snake_case  (		nn.Module					):



   '''simple docstring'''






   def        UpperCamelCase_					(   self							:     List[Any]			,						lowerCAmelCase							:     int			,						lowerCAmelCase							:     List[Any]=0.707_107			,						lowerCAmelCase							:     Optional[Any]=0.282_095)			->			List[Any]:

    """simple docstring"""







    _snake_case      :					List[str]					=   (input - mu).div(sigma * math.sqrt(2.0))
    return 0.5 * (1.0 + torch.erf(lowerCAmelCase))







class 						snake_case  (		nn.Module					):



   '''simple docstring'''






   def        UpperCamelCase_					(   self							:     Any			,						lowerCAmelCase							:     Dict)			->			Union[str, Any]:

    """simple docstring"""







    _snake_case      :					Dict					=   nn.functional.relu(lowerCAmelCase)
    _snake_case      :					Tuple					=   torch.square(lowerCAmelCase)
    return squared







class 						snake_case  (		SCREAMING_SNAKE_CASE_					):



   '''simple docstring'''






   def __getitem__(   self							:     Dict			,						lowerCAmelCase							:     Tuple)			->			str:

    """simple docstring"""







    _snake_case      :					Optional[Any]					=   super().__getitem__(lowerCAmelCase)
    _snake_case		,      _snake_case      :					List[str]					=   content if isinstance(lowerCAmelCase			,						lowerCAmelCase) else (content, {})
    return cls(**lowerCAmelCase)
a__      =		{
    """gelu""": GELUActivation,
    """gelu_10""": (ClippedGELUActivation, {"""min""": -10, """max""": 10}),
    """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__      =		ClassInstantier(ACTaCLS)



def  lowercase    (				SCREAMING_SNAKE_CASE__    :		Any			)					->       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__      =		get_activation("""gelu_python""")
a__      =		get_activation("""gelu_new""")
a__      =		get_activation("""gelu""")
a__      =		get_activation("""gelu_fast""")
a__      =		get_activation("""quick_gelu""")
a__      =		get_activation("""silu""")
a__      =		get_activation("""mish""")

a__      =		get_activation("""linear""")
