activations.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import math
  15. from collections import OrderedDict
  16. import paddle
  17. import paddle.nn.functional as F
  18. from paddle import Tensor, nn
  19. class NewGELUActivation(nn.Layer):
  20. """
  21. Implementation of the GELU activation function currently in Google BERT repo (identical to OpenAI GPT). Also see
  22. the Gaussian Error Linear Units paper: https://arxiv.org/abs/1606.08415
  23. """
  24. def forward(self, input: Tensor) -> Tensor:
  25. return (
  26. 0.5
  27. * input
  28. * (
  29. 1.0
  30. + paddle.tanh(
  31. math.sqrt(2.0 / math.pi)
  32. * (input + 0.044715 * paddle.pow(input, 3.0))
  33. )
  34. )
  35. )
  36. class GELUActivation(nn.Layer):
  37. """
  38. Original Implementation of the GELU activation function in Google BERT repo when initially created. For
  39. information: OpenAI GPT's GELU is slightly different (and gives slightly different results): 0.5 * x * (1 +
  40. torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) This is now written in C in nn.functional
  41. Also see the Gaussian Error Linear Units paper: https://arxiv.org/abs/1606.08415
  42. """
  43. def __init__(self, use_gelu_python: bool = False):
  44. super().__init__()
  45. if use_gelu_python:
  46. self.act = self._gelu_python
  47. else:
  48. self.act = nn.functional.gelu
  49. def _gelu_python(self, input: Tensor) -> Tensor:
  50. return input * 0.5 * (1.0 + paddle.erf(input / math.sqrt(2.0)))
  51. def forward(self, input: Tensor) -> Tensor:
  52. return self.act(input)
  53. class FastGELUActivation(nn.Layer):
  54. """
  55. Applies GELU approximation that is slower than QuickGELU but more accurate. See: https://github.com/hendrycks/GELUs
  56. """
  57. def forward(self, input: Tensor) -> Tensor:
  58. return (
  59. 0.5
  60. * input
  61. * (
  62. 1.0
  63. + paddle.tanh(input * 0.7978845608 * (1.0 + 0.044715 * input * input))
  64. )
  65. )
  66. class QuickGELUActivation(nn.Layer):
  67. """
  68. Applies GELU approximation that is fast but somewhat inaccurate. See: https://github.com/hendrycks/GELUs
  69. """
  70. def forward(self, input: Tensor) -> Tensor:
  71. return input * F.sigmoid(1.702 * input)
  72. class ClippedGELUActivation(nn.Layer):
  73. """
  74. Clip the range of possible GeLU outputs between [min, max]. This is especially useful for quantization purpose, as
  75. it allows mapping negatives values in the GeLU spectrum. For more information on this trick, please refer to
  76. https://arxiv.org/abs/2004.09602.
  77. Gaussian Error Linear Unit. Original Implementation of the gelu activation function in Google Bert repo when
  78. initially created.
  79. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results): 0.5 * x * (1 +
  80. torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))). See https://arxiv.org/abs/1606.08415
  81. """
  82. def __init__(self, min: float, max: float):
  83. if min > max:
  84. raise ValueError(f"min should be < max (got min: {min}, max: {max})")
  85. super().__init__()
  86. self.min = min
  87. self.max = max
  88. def forward(self, x: Tensor) -> Tensor:
  89. return paddle.clip(gelu(x), self.min, self.max)
  90. class SiLUActivation(nn.Layer):
  91. """
  92. See Gaussian Error Linear Units (Hendrycks et al., https://arxiv.org/abs/1606.08415) where the SiLU (Sigmoid Linear
  93. Unit) was originally introduced and coined, and see Sigmoid-Weighted Linear Units for Neural Network Function
  94. Approximation in Reinforcement Learning (Elfwing et al., https://arxiv.org/abs/1702.03118) and Swish: a Self-Gated
  95. Activation Function (Ramachandran et al., https://arxiv.org/abs/1710.05941v1) where the SiLU was experimented with
  96. later.
  97. """
  98. def forward(self, input: Tensor) -> Tensor:
  99. return F.silu(input)
  100. class MishActivation(nn.Layer):
  101. """
  102. See Mish: A Self-Regularized Non-Monotonic Activation Function (Misra., https://arxiv.org/abs/1908.08681). Also
  103. visit the official repository for the paper: https://github.com/digantamisra98/Mish
  104. """
  105. def forward(self, input: Tensor) -> Tensor:
  106. return F.mish(input)
  107. class LinearActivation(nn.Layer):
  108. """
  109. Applies the linear activation function, i.e. forwarding input directly to output.
  110. """
  111. def forward(self, input: Tensor) -> Tensor:
  112. return input
  113. class ClassInstantier(OrderedDict):
  114. def __getitem__(self, key):
  115. content = super().__getitem__(key)
  116. cls, kwargs = content if isinstance(content, tuple) else (content, {})
  117. return cls(**kwargs)
  118. ACT2CLS = {
  119. "gelu": GELUActivation,
  120. "gelu_10": (ClippedGELUActivation, {"min": -10, "max": 10}),
  121. "gelu_fast": FastGELUActivation,
  122. "gelu_new": NewGELUActivation,
  123. "gelu_python": (GELUActivation, {"use_gelu_python": True}),
  124. "linear": LinearActivation,
  125. "mish": MishActivation,
  126. "quick_gelu": QuickGELUActivation,
  127. "relu": nn.ReLU,
  128. "relu6": nn.ReLU6,
  129. "sigmoid": nn.Sigmoid,
  130. "silu": SiLUActivation,
  131. "swish": SiLUActivation,
  132. "tanh": nn.Tanh,
  133. }
  134. ACT2FN = ClassInstantier(ACT2CLS)
  135. def get_activation(activation_string):
  136. if activation_string in ACT2FN:
  137. return ACT2FN[activation_string]
  138. else:
  139. raise KeyError(
  140. f"function {activation_string} not found in ACT2FN mapping {list(ACT2FN.keys())}"
  141. )
  142. gelu_python = get_activation("gelu_python")
  143. gelu_new = get_activation("gelu_new")
  144. gelu = get_activation("gelu")
  145. gelu_fast = get_activation("gelu_fast")
  146. quick_gelu = get_activation("quick_gelu")
  147. silu = get_activation("silu")
  148. mish = get_activation("mish")
  149. linear_act = get_activation("linear")