

import math
from collections import OrderedDict

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

from .utils import logging


lowerCAmelCase__             =		logging.get_logger(__name__)







class 						lowercase     (					nn.Module				):


		"""simple docstring"""




		def __init__(					self):
			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 		A__       (					self						,							__snake_case):
			return nn.functional.gelu(__snake_case						,							approximate='tanh')







class 						lowercase     (					nn.Module				):


		"""simple docstring"""




		def 		A__       (					self						,							__snake_case):
			return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (input + 0.0_4_4_7_1_5 * torch.pow(__snake_case						,							3.0))))







class 						lowercase     (					nn.Module				):


		"""simple docstring"""




		def __init__(					self						,							__snake_case = False):
			super().__init__()
			if use_gelu_python:
				_UpperCamelCase :		List[Any]								=    self._gelu_python
			else:
				_UpperCamelCase :		Optional[int]								=    nn.functional.gelu


		def 		A__       (					self						,							__snake_case):
			return input * 0.5 * (1.0 + torch.erf(input / math.sqrt(2.0)))






		def 		A__       (					self						,							__snake_case):
			return self.act(__snake_case)







class 						lowercase     (					nn.Module				):


		"""simple docstring"""




		def 		A__       (					self						,							__snake_case):
			return 0.5 * input * (1.0 + torch.tanh(input * 0.7_9_7_8_8_4_5_6_0_8 * (1.0 + 0.0_4_4_7_1_5 * input * input)))







class 						lowercase     (					nn.Module				):


		"""simple docstring"""




		def 		A__       (					self						,							__snake_case):
			return input * torch.sigmoid(1.7_0_2 * input)







class 						lowercase     (					nn.Module				):


		"""simple docstring"""




		def __init__(					self						,							__snake_case						,							__snake_case):
			if min > max:
				raise ValueError(f'''min should be < max (got min: {min}, max: {max})''')

			super().__init__()
			_UpperCamelCase :		List[str]								=    min
			_UpperCamelCase :		Optional[Any]								=    max






		def 		A__       (					self						,							__snake_case):
			return torch.clip(gelu(__snake_case)						,							self.min						,							self.max)







class 						lowercase     (					nn.Module				):


		"""simple docstring"""




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






		def 		A__       (					self						,							__snake_case):
			return 0.5 * input * (1 + torch.tanh(self.precomputed_constant * (input + 0.0_4_4_7_1_5 * torch.pow(__snake_case						,							3))))







class 						lowercase     (					nn.Module				):


		"""simple docstring"""




		def 		A__       (					self						,							__snake_case):
			return nn.functional.silu(__snake_case)







class 						lowercase     (					nn.Module				):


		"""simple docstring"""




		def __init__(					self):
			super().__init__()
			if version.parse(torch.__version__) < version.parse('1.9.0'):
				_UpperCamelCase :		Dict								=    self._mish_python
			else:
				_UpperCamelCase :		Optional[int]								=    nn.functional.mish


		def 		A__       (					self						,							__snake_case):
			return input * torch.tanh(nn.functional.softplus(__snake_case))






		def 		A__       (					self						,							__snake_case):
			return self.act(__snake_case)







class 						lowercase     (					nn.Module				):


		"""simple docstring"""




		def 		A__       (					self						,							__snake_case):
			return input







class 						lowercase     (					nn.Module				):


		"""simple docstring"""




		def 		A__       (					self						,							__snake_case						,							__snake_case=0.7_0_7_1_0_7						,							__snake_case=0.2_8_2_0_9_5):
			_UpperCamelCase :		Any								=    (input - mu).div(sigma * math.sqrt(2.0))
			return 0.5 * (1.0 + torch.erf(__snake_case))







class 						lowercase     (					nn.Module				):


		"""simple docstring"""




		def 		A__       (					self						,							__snake_case):
			_UpperCamelCase :		Tuple								=    nn.functional.relu(__snake_case)
			_UpperCamelCase :		int								=    torch.square(__snake_case)
			return squared







class 						lowercase     (					_lowercase				):


		"""simple docstring"""




		def __getitem__(					self						,							__snake_case):
			_UpperCamelCase :		Dict								=    super().__getitem__(__snake_case)
			_UpperCamelCase						,		_UpperCamelCase :		Union[str, Any]								=    content if isinstance(__snake_case						,							__snake_case) else (content, {})
			return cls(**__snake_case)

lowerCAmelCase__             =		{
    """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,
}
lowerCAmelCase__             =		ClassInstantier(ACTaCLS)






def        lowerCamelCase_  (				UpperCAmelCase_				:  Optional[Any]						)    ->					str:




	'''simple docstring'''




	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
lowerCAmelCase__             =		get_activation("""gelu_python""")
lowerCAmelCase__             =		get_activation("""gelu_new""")
lowerCAmelCase__             =		get_activation("""gelu""")
lowerCAmelCase__             =		get_activation("""gelu_fast""")
lowerCAmelCase__             =		get_activation("""quick_gelu""")
lowerCAmelCase__             =		get_activation("""silu""")
lowerCAmelCase__             =		get_activation("""mish""")







lowerCAmelCase__             =		get_activation("""linear""")







import posixpath
from pathlib import Path
from unittest.mock import patch

import pytest
from fsspec.implementations.local import AbstractFileSystem, LocalFileSystem, stringify_path
from fsspec.registry import _registry as _fsspec_registry







class 						lowercase     (					_lowercase				):


		"""simple docstring"""




		a__       							=	"mock"


		def __init__(					self						,							*__snake_case						,							__snake_case						,							**__snake_case):
			super().__init__()
			_UpperCamelCase :		str								=    LocalFileSystem(*__snake_case						,							**__snake_case)
			_UpperCamelCase :		str								=    Path(__snake_case).resolve().as_posix() + '/'


		def 		A__       (					self						,							__snake_case						,							*__snake_case						,							**__snake_case):
			_UpperCamelCase :		int								=    posixpath.join(self.local_root_dir						,							self._strip_protocol(__snake_case))
			return self._fs.mkdir(__snake_case						,							*__snake_case						,							**__snake_case)


		def 		A__       (					self						,							__snake_case						,							*__snake_case						,							**__snake_case):
			_UpperCamelCase :		List[str]								=    posixpath.join(self.local_root_dir						,							self._strip_protocol(__snake_case))
			return self._fs.makedirs(__snake_case						,							*__snake_case						,							**__snake_case)


		def 		A__       (					self						,							__snake_case):
			_UpperCamelCase :		Dict								=    posixpath.join(self.local_root_dir						,							self._strip_protocol(__snake_case))
			return self._fs.rmdir(__snake_case)


		def 		A__       (					self						,							__snake_case						,							__snake_case=True						,							*__snake_case						,							**__snake_case):
			_UpperCamelCase :		Union[str, Any]								=    posixpath.join(self.local_root_dir						,							self._strip_protocol(__snake_case))
			_UpperCamelCase :		Tuple								=    self._fs.ls(__snake_case						,							detail=__snake_case						,							*__snake_case						,							**__snake_case)
			if detail:
				return [{**info, "name": info["name"][len(self.local_root_dir) :]} for info in out]
			else:
				return [name[len(self.local_root_dir) :] for name in out]


		def 		A__       (					self						,							__snake_case						,							*__snake_case						,							**__snake_case):
			_UpperCamelCase :		Optional[Any]								=    posixpath.join(self.local_root_dir						,							self._strip_protocol(__snake_case))
			_UpperCamelCase :		Optional[Any]								=    dict(self._fs.info(__snake_case						,							*__snake_case						,							**__snake_case))
			_UpperCamelCase :		Dict								=    out['name'][len(self.local_root_dir) :]
			return out


		def 		A__       (					self						,							__snake_case						,							__snake_case						,							*__snake_case						,							**__snake_case):
			_UpperCamelCase :		str								=    posixpath.join(self.local_root_dir						,							self._strip_protocol(__snake_case))
			_UpperCamelCase :		Tuple								=    posixpath.join(self.local_root_dir						,							self._strip_protocol(__snake_case))
			return self._fs.cp_file(__snake_case						,							__snake_case						,							*__snake_case						,							**__snake_case)


		def 		A__       (					self						,							__snake_case						,							*__snake_case						,							**__snake_case):
			_UpperCamelCase :		Dict								=    posixpath.join(self.local_root_dir						,							self._strip_protocol(__snake_case))
			return self._fs.rm_file(__snake_case						,							*__snake_case						,							**__snake_case)


		def 		A__       (					self						,							__snake_case						,							*__snake_case						,							**__snake_case):
			_UpperCamelCase :		int								=    posixpath.join(self.local_root_dir						,							self._strip_protocol(__snake_case))
			return self._fs.rm(__snake_case						,							*__snake_case						,							**__snake_case)


		def 		A__       (					self						,							__snake_case						,							*__snake_case						,							**__snake_case):
			_UpperCamelCase :		Dict								=    posixpath.join(self.local_root_dir						,							self._strip_protocol(__snake_case))
			return self._fs._open(__snake_case						,							*__snake_case						,							**__snake_case)


		def 		A__       (					self						,							__snake_case):
			_UpperCamelCase :		Dict								=    posixpath.join(self.local_root_dir						,							self._strip_protocol(__snake_case))
			return self._fs.created(__snake_case)


		def 		A__       (					self						,							__snake_case):
			_UpperCamelCase :		Dict								=    posixpath.join(self.local_root_dir						,							self._strip_protocol(__snake_case))
			return self._fs.modified(__snake_case)






		@classmethod
		def 		A__       (					cls						,							__snake_case):
			_UpperCamelCase :		List[Any]								=    stringify_path(__snake_case)
			if path.startswith('mock://'):
				_UpperCamelCase :		int								=    path[7:]
			return path







class 						lowercase     (					_lowercase				):


		"""simple docstring"""




		a__       							=	"tmp"
		a__       							=	None


		def __init__(					self						,							*__snake_case						,							**__snake_case):
			assert self.tmp_dir is not None, "TmpDirFileSystem.tmp_dir is not set"
			super().__init__(*__snake_case						,							**__snake_case						,							local_root_dir=self.tmp_dir						,							auto_mkdir=__snake_case)






		@classmethod
		def 		A__       (					cls						,							__snake_case):
			_UpperCamelCase :		Optional[int]								=    stringify_path(__snake_case)
			if path.startswith('tmp://'):
				_UpperCamelCase :		Optional[Any]								=    path[6:]
			return path






@pytest.fixture
def        lowerCamelCase_  (				)    ->					Dict:




	'''simple docstring'''




	_UpperCamelCase :		List[str]								=    MockFileSystem
	_UpperCamelCase :		Optional[int]								=    TmpDirFileSystem
	yield
	del _fsspec_registry["mock"]
	del _fsspec_registry["tmp"]






@pytest.fixture
def        lowerCamelCase_  (				UpperCAmelCase_				:  Any				,							UpperCAmelCase_				:  Optional[int]						)    ->					Optional[int]:




	'''simple docstring'''




	_UpperCamelCase :		str								=    tmp_path_factory.mktemp('mockfs'						)
	return MockFileSystem(local_root_dir=UpperCAmelCase_				,							auto_mkdir=UpperCAmelCase_						)







@pytest.fixture
def        lowerCamelCase_  (				UpperCAmelCase_				:  Tuple				,							UpperCAmelCase_				:  Union[str, Any]						)    ->					int:




	'''simple docstring'''




	_UpperCamelCase :		Dict								=    tmp_path_factory.mktemp('tmpfs'						)
	with patch.object(UpperCAmelCase_				,							'tmp_dir'				,							UpperCAmelCase_						):
		yield TmpDirFileSystem()




