activation.py 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902
  1. # mypy: allow-untyped-defs
  2. import warnings
  3. from typing import Optional
  4. import torch
  5. import torch.nn.functional as F
  6. from torch import Tensor
  7. from torch.nn.init import constant_, xavier_normal_, xavier_uniform_
  8. from torch.nn.parameter import Parameter
  9. from .linear import NonDynamicallyQuantizableLinear
  10. from .module import Module
  11. __all__ = [
  12. "Threshold",
  13. "ReLU",
  14. "RReLU",
  15. "Hardtanh",
  16. "ReLU6",
  17. "Sigmoid",
  18. "Hardsigmoid",
  19. "Tanh",
  20. "SiLU",
  21. "Mish",
  22. "Hardswish",
  23. "ELU",
  24. "CELU",
  25. "SELU",
  26. "GLU",
  27. "GELU",
  28. "Hardshrink",
  29. "LeakyReLU",
  30. "LogSigmoid",
  31. "Softplus",
  32. "Softshrink",
  33. "MultiheadAttention",
  34. "PReLU",
  35. "Softsign",
  36. "Tanhshrink",
  37. "Softmin",
  38. "Softmax",
  39. "Softmax2d",
  40. "LogSoftmax",
  41. ]
  42. class Threshold(Module):
  43. r"""Thresholds each element of the input Tensor.
  44. Threshold is defined as:
  45. .. math::
  46. y =
  47. \begin{cases}
  48. x, &\text{ if } x > \text{threshold} \\
  49. \text{value}, &\text{ otherwise }
  50. \end{cases}
  51. Args:
  52. threshold: The value to threshold at
  53. value: The value to replace with
  54. inplace: can optionally do the operation in-place. Default: ``False``
  55. Shape:
  56. - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
  57. - Output: :math:`(*)`, same shape as the input.
  58. .. image:: ../scripts/activation_images/Threshold.png
  59. Examples::
  60. >>> m = nn.Threshold(0, 0.5)
  61. >>> input = torch.arange(-3, 3)
  62. >>> output = m(input)
  63. """
  64. __constants__ = ["threshold", "value", "inplace"]
  65. threshold: float
  66. value: float
  67. inplace: bool
  68. def __init__(self, threshold: float, value: float, inplace: bool = False) -> None:
  69. super().__init__()
  70. self.threshold = threshold
  71. self.value = value
  72. self.inplace = inplace
  73. # TODO: check in THNN (if inplace == True, then assert value <= threshold)
  74. def forward(self, input: Tensor) -> Tensor:
  75. """
  76. Runs the forward pass.
  77. """
  78. return F.threshold(input, self.threshold, self.value, self.inplace)
  79. def extra_repr(self) -> str:
  80. """
  81. Return the extra representation of the module.
  82. """
  83. inplace_str = ", inplace=True" if self.inplace else ""
  84. return f"threshold={self.threshold}, value={self.value}{inplace_str}"
  85. class ReLU(Module):
  86. r"""Applies the rectified linear unit function element-wise.
  87. :math:`\text{ReLU}(x) = (x)^+ = \max(0, x)`
  88. Args:
  89. inplace: can optionally do the operation in-place. Default: ``False``
  90. Shape:
  91. - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
  92. - Output: :math:`(*)`, same shape as the input.
  93. .. image:: ../scripts/activation_images/ReLU.png
  94. Examples::
  95. >>> m = nn.ReLU()
  96. >>> input = torch.randn(2)
  97. >>> output = m(input)
  98. An implementation of CReLU - https://arxiv.org/abs/1603.05201
  99. >>> m = nn.ReLU()
  100. >>> input = torch.randn(2).unsqueeze(0)
  101. >>> output = torch.cat((m(input), m(-input)))
  102. """
  103. __constants__ = ["inplace"]
  104. inplace: bool
  105. def __init__(self, inplace: bool = False) -> None:
  106. super().__init__()
  107. self.inplace = inplace
  108. def forward(self, input: Tensor) -> Tensor:
  109. """
  110. Runs the forward pass.
  111. """
  112. return F.relu(input, inplace=self.inplace)
  113. def extra_repr(self) -> str:
  114. """
  115. Return the extra representation of the module.
  116. """
  117. inplace_str = "inplace=True" if self.inplace else ""
  118. return inplace_str
  119. class RReLU(Module):
  120. r"""Applies the randomized leaky rectified linear unit function, element-wise.
  121. Method described in the paper:
  122. `Empirical Evaluation of Rectified Activations in Convolutional Network <https://arxiv.org/abs/1505.00853>`_.
  123. The function is defined as:
  124. .. math::
  125. \text{RReLU}(x) =
  126. \begin{cases}
  127. x & \text{if } x \geq 0 \\
  128. ax & \text{ otherwise }
  129. \end{cases}
  130. where :math:`a` is randomly sampled from uniform distribution
  131. :math:`\mathcal{U}(\text{lower}, \text{upper})` during training while during
  132. evaluation :math:`a` is fixed with :math:`a = \frac{\text{lower} + \text{upper}}{2}`.
  133. Args:
  134. lower: lower bound of the uniform distribution. Default: :math:`\frac{1}{8}`
  135. upper: upper bound of the uniform distribution. Default: :math:`\frac{1}{3}`
  136. inplace: can optionally do the operation in-place. Default: ``False``
  137. Shape:
  138. - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
  139. - Output: :math:`(*)`, same shape as the input.
  140. .. image:: ../scripts/activation_images/RReLU.png
  141. Examples::
  142. >>> m = nn.RReLU(0.1, 0.3)
  143. >>> input = torch.randn(2)
  144. >>> output = m(input)
  145. """
  146. __constants__ = ["lower", "upper", "inplace"]
  147. lower: float
  148. upper: float
  149. inplace: bool
  150. def __init__(
  151. self, lower: float = 1.0 / 8, upper: float = 1.0 / 3, inplace: bool = False
  152. ) -> None:
  153. super().__init__()
  154. self.lower = lower
  155. self.upper = upper
  156. self.inplace = inplace
  157. def forward(self, input: Tensor) -> Tensor:
  158. """
  159. Runs the forward pass.
  160. """
  161. return F.rrelu(input, self.lower, self.upper, self.training, self.inplace)
  162. def extra_repr(self) -> str:
  163. """
  164. Return the extra representation of the module.
  165. """
  166. inplace_str = ", inplace=True" if self.inplace else ""
  167. return f"lower={self.lower}, upper={self.upper}{inplace_str}"
  168. class Hardtanh(Module):
  169. r"""Applies the HardTanh function element-wise.
  170. HardTanh is defined as:
  171. .. math::
  172. \text{HardTanh}(x) = \begin{cases}
  173. \text{max\_val} & \text{ if } x > \text{ max\_val } \\
  174. \text{min\_val} & \text{ if } x < \text{ min\_val } \\
  175. x & \text{ otherwise } \\
  176. \end{cases}
  177. Args:
  178. min_val: minimum value of the linear region range. Default: -1
  179. max_val: maximum value of the linear region range. Default: 1
  180. inplace: can optionally do the operation in-place. Default: ``False``
  181. Keyword arguments :attr:`min_value` and :attr:`max_value`
  182. have been deprecated in favor of :attr:`min_val` and :attr:`max_val`.
  183. Shape:
  184. - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
  185. - Output: :math:`(*)`, same shape as the input.
  186. .. image:: ../scripts/activation_images/Hardtanh.png
  187. Examples::
  188. >>> m = nn.Hardtanh(-2, 2)
  189. >>> input = torch.randn(2)
  190. >>> output = m(input)
  191. """
  192. __constants__ = ["min_val", "max_val", "inplace"]
  193. min_val: float
  194. max_val: float
  195. inplace: bool
  196. def __init__(
  197. self,
  198. min_val: float = -1.0,
  199. max_val: float = 1.0,
  200. inplace: bool = False,
  201. min_value: Optional[float] = None,
  202. max_value: Optional[float] = None,
  203. ) -> None:
  204. super().__init__()
  205. if min_value is not None:
  206. warnings.warn(
  207. "keyword argument `min_value` is deprecated and rename to `min_val`",
  208. FutureWarning,
  209. stacklevel=2,
  210. )
  211. min_val = min_value
  212. if max_value is not None:
  213. warnings.warn(
  214. "keyword argument `max_value` is deprecated and rename to `max_val`",
  215. FutureWarning,
  216. stacklevel=2,
  217. )
  218. max_val = max_value
  219. self.min_val = min_val
  220. self.max_val = max_val
  221. self.inplace = inplace
  222. assert self.max_val > self.min_val
  223. def forward(self, input: Tensor) -> Tensor:
  224. """
  225. Runs the forward pass.
  226. """
  227. return F.hardtanh(input, self.min_val, self.max_val, self.inplace)
  228. def extra_repr(self) -> str:
  229. """
  230. Return the extra representation of the module.
  231. """
  232. inplace_str = ", inplace=True" if self.inplace else ""
  233. return f"min_val={self.min_val}, max_val={self.max_val}{inplace_str}"
  234. class ReLU6(Hardtanh):
  235. r"""Applies the ReLU6 function element-wise.
  236. .. math::
  237. \text{ReLU6}(x) = \min(\max(0,x), 6)
  238. Args:
  239. inplace: can optionally do the operation in-place. Default: ``False``
  240. Shape:
  241. - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
  242. - Output: :math:`(*)`, same shape as the input.
  243. .. image:: ../scripts/activation_images/ReLU6.png
  244. Examples::
  245. >>> m = nn.ReLU6()
  246. >>> input = torch.randn(2)
  247. >>> output = m(input)
  248. """
  249. def __init__(self, inplace: bool = False) -> None:
  250. super().__init__(0.0, 6.0, inplace)
  251. def extra_repr(self) -> str:
  252. """
  253. Return the extra representation of the module.
  254. """
  255. inplace_str = "inplace=True" if self.inplace else ""
  256. return inplace_str
  257. class Sigmoid(Module):
  258. r"""Applies the Sigmoid function element-wise.
  259. .. math::
  260. \text{Sigmoid}(x) = \sigma(x) = \frac{1}{1 + \exp(-x)}
  261. Shape:
  262. - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
  263. - Output: :math:`(*)`, same shape as the input.
  264. .. image:: ../scripts/activation_images/Sigmoid.png
  265. Examples::
  266. >>> m = nn.Sigmoid()
  267. >>> input = torch.randn(2)
  268. >>> output = m(input)
  269. """
  270. def forward(self, input: Tensor) -> Tensor:
  271. """
  272. Runs the forward pass.
  273. """
  274. return torch.sigmoid(input)
  275. class Hardsigmoid(Module):
  276. r"""Applies the Hardsigmoid function element-wise.
  277. Hardsigmoid is defined as:
  278. .. math::
  279. \text{Hardsigmoid}(x) = \begin{cases}
  280. 0 & \text{if~} x \le -3, \\
  281. 1 & \text{if~} x \ge +3, \\
  282. x / 6 + 1 / 2 & \text{otherwise}
  283. \end{cases}
  284. Args:
  285. inplace: can optionally do the operation in-place. Default: ``False``
  286. Shape:
  287. - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
  288. - Output: :math:`(*)`, same shape as the input.
  289. .. image:: ../scripts/activation_images/Hardsigmoid.png
  290. Examples::
  291. >>> m = nn.Hardsigmoid()
  292. >>> input = torch.randn(2)
  293. >>> output = m(input)
  294. """
  295. __constants__ = ["inplace"]
  296. inplace: bool
  297. def __init__(self, inplace: bool = False) -> None:
  298. super().__init__()
  299. self.inplace = inplace
  300. def forward(self, input: Tensor) -> Tensor:
  301. """
  302. Runs the forward pass.
  303. """
  304. return F.hardsigmoid(input, self.inplace)
  305. class Tanh(Module):
  306. r"""Applies the Hyperbolic Tangent (Tanh) function element-wise.
  307. Tanh is defined as:
  308. .. math::
  309. \text{Tanh}(x) = \tanh(x) = \frac{\exp(x) - \exp(-x)} {\exp(x) + \exp(-x)}
  310. Shape:
  311. - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
  312. - Output: :math:`(*)`, same shape as the input.
  313. .. image:: ../scripts/activation_images/Tanh.png
  314. Examples::
  315. >>> m = nn.Tanh()
  316. >>> input = torch.randn(2)
  317. >>> output = m(input)
  318. """
  319. def forward(self, input: Tensor) -> Tensor:
  320. """
  321. Runs the forward pass.
  322. """
  323. return torch.tanh(input)
  324. class SiLU(Module):
  325. r"""Applies the Sigmoid Linear Unit (SiLU) function, element-wise.
  326. The SiLU function is also known as the swish function.
  327. .. math::
  328. \text{silu}(x) = x * \sigma(x), \text{where } \sigma(x) \text{ is the logistic sigmoid.}
  329. .. note::
  330. See `Gaussian Error Linear Units (GELUs) <https://arxiv.org/abs/1606.08415>`_
  331. where the SiLU (Sigmoid Linear Unit) was originally coined, and see
  332. `Sigmoid-Weighted Linear Units for Neural Network Function Approximation
  333. in Reinforcement Learning <https://arxiv.org/abs/1702.03118>`_ and `Swish:
  334. a Self-Gated Activation Function <https://arxiv.org/abs/1710.05941v1>`_
  335. where the SiLU was experimented with later.
  336. Shape:
  337. - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
  338. - Output: :math:`(*)`, same shape as the input.
  339. .. image:: ../scripts/activation_images/SiLU.png
  340. Examples::
  341. >>> m = nn.SiLU()
  342. >>> input = torch.randn(2)
  343. >>> output = m(input)
  344. """
  345. __constants__ = ["inplace"]
  346. inplace: bool
  347. def __init__(self, inplace: bool = False) -> None:
  348. super().__init__()
  349. self.inplace = inplace
  350. def forward(self, input: Tensor) -> Tensor:
  351. """
  352. Runs the forward pass.
  353. """
  354. return F.silu(input, inplace=self.inplace)
  355. def extra_repr(self) -> str:
  356. """
  357. Return the extra representation of the module.
  358. """
  359. inplace_str = "inplace=True" if self.inplace else ""
  360. return inplace_str
  361. class Mish(Module):
  362. r"""Applies the Mish function, element-wise.
  363. Mish: A Self Regularized Non-Monotonic Neural Activation Function.
  364. .. math::
  365. \text{Mish}(x) = x * \text{Tanh}(\text{Softplus}(x))
  366. .. note::
  367. See `Mish: A Self Regularized Non-Monotonic Neural Activation Function <https://arxiv.org/abs/1908.08681>`_
  368. Shape:
  369. - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
  370. - Output: :math:`(*)`, same shape as the input.
  371. .. image:: ../scripts/activation_images/Mish.png
  372. Examples::
  373. >>> m = nn.Mish()
  374. >>> input = torch.randn(2)
  375. >>> output = m(input)
  376. """
  377. __constants__ = ["inplace"]
  378. inplace: bool
  379. def __init__(self, inplace: bool = False) -> None:
  380. super().__init__()
  381. self.inplace = inplace
  382. def forward(self, input: Tensor) -> Tensor:
  383. """
  384. Runs the forward pass.
  385. """
  386. return F.mish(input, inplace=self.inplace)
  387. def extra_repr(self) -> str:
  388. """
  389. Return the extra representation of the module.
  390. """
  391. inplace_str = "inplace=True" if self.inplace else ""
  392. return inplace_str
  393. class Hardswish(Module):
  394. r"""Applies the Hardswish function, element-wise.
  395. Method described in the paper: `Searching for MobileNetV3 <https://arxiv.org/abs/1905.02244>`_.
  396. Hardswish is defined as:
  397. .. math::
  398. \text{Hardswish}(x) = \begin{cases}
  399. 0 & \text{if~} x \le -3, \\
  400. x & \text{if~} x \ge +3, \\
  401. x \cdot (x + 3) /6 & \text{otherwise}
  402. \end{cases}
  403. Args:
  404. inplace: can optionally do the operation in-place. Default: ``False``
  405. Shape:
  406. - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
  407. - Output: :math:`(*)`, same shape as the input.
  408. .. image:: ../scripts/activation_images/Hardswish.png
  409. Examples::
  410. >>> m = nn.Hardswish()
  411. >>> input = torch.randn(2)
  412. >>> output = m(input)
  413. """
  414. __constants__ = ["inplace"]
  415. inplace: bool
  416. def __init__(self, inplace: bool = False) -> None:
  417. super().__init__()
  418. self.inplace = inplace
  419. def forward(self, input: Tensor) -> Tensor:
  420. """
  421. Runs the forward pass.
  422. """
  423. return F.hardswish(input, self.inplace)
  424. class ELU(Module):
  425. r"""Applies the Exponential Linear Unit (ELU) function, element-wise.
  426. Method described in the paper: `Fast and Accurate Deep Network Learning by Exponential Linear
  427. Units (ELUs) <https://arxiv.org/abs/1511.07289>`__.
  428. ELU is defined as:
  429. .. math::
  430. \text{ELU}(x) = \begin{cases}
  431. x, & \text{ if } x > 0\\
  432. \alpha * (\exp(x) - 1), & \text{ if } x \leq 0
  433. \end{cases}
  434. Args:
  435. alpha: the :math:`\alpha` value for the ELU formulation. Default: 1.0
  436. inplace: can optionally do the operation in-place. Default: ``False``
  437. Shape:
  438. - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
  439. - Output: :math:`(*)`, same shape as the input.
  440. .. image:: ../scripts/activation_images/ELU.png
  441. Examples::
  442. >>> m = nn.ELU()
  443. >>> input = torch.randn(2)
  444. >>> output = m(input)
  445. """
  446. __constants__ = ["alpha", "inplace"]
  447. alpha: float
  448. inplace: bool
  449. def __init__(self, alpha: float = 1.0, inplace: bool = False) -> None:
  450. super().__init__()
  451. self.alpha = alpha
  452. self.inplace = inplace
  453. def forward(self, input: Tensor) -> Tensor:
  454. """
  455. Runs the forward pass.
  456. """
  457. return F.elu(input, self.alpha, self.inplace)
  458. def extra_repr(self) -> str:
  459. """
  460. Return the extra representation of the module.
  461. """
  462. inplace_str = ", inplace=True" if self.inplace else ""
  463. return f"alpha={self.alpha}{inplace_str}"
  464. class CELU(Module):
  465. r"""Applies the CELU function element-wise.
  466. .. math::
  467. \text{CELU}(x) = \max(0,x) + \min(0, \alpha * (\exp(x/\alpha) - 1))
  468. More details can be found in the paper `Continuously Differentiable Exponential Linear Units`_ .
  469. Args:
  470. alpha: the :math:`\alpha` value for the CELU formulation. Default: 1.0
  471. inplace: can optionally do the operation in-place. Default: ``False``
  472. Shape:
  473. - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
  474. - Output: :math:`(*)`, same shape as the input.
  475. .. image:: ../scripts/activation_images/CELU.png
  476. Examples::
  477. >>> m = nn.CELU()
  478. >>> input = torch.randn(2)
  479. >>> output = m(input)
  480. .. _`Continuously Differentiable Exponential Linear Units`:
  481. https://arxiv.org/abs/1704.07483
  482. """
  483. __constants__ = ["alpha", "inplace"]
  484. alpha: float
  485. inplace: bool
  486. def __init__(self, alpha: float = 1.0, inplace: bool = False) -> None:
  487. super().__init__()
  488. self.alpha = alpha
  489. self.inplace = inplace
  490. def forward(self, input: Tensor) -> Tensor:
  491. """
  492. Runs the forward pass.
  493. """
  494. return F.celu(input, self.alpha, self.inplace)
  495. def extra_repr(self) -> str:
  496. """
  497. Return the extra representation of the module.
  498. """
  499. inplace_str = ", inplace=True" if self.inplace else ""
  500. return f"alpha={self.alpha}{inplace_str}"
  501. class SELU(Module):
  502. r"""Applies the SELU function element-wise.
  503. .. math::
  504. \text{SELU}(x) = \text{scale} * (\max(0,x) + \min(0, \alpha * (\exp(x) - 1)))
  505. with :math:`\alpha = 1.6732632423543772848170429916717` and
  506. :math:`\text{scale} = 1.0507009873554804934193349852946`.
  507. .. warning::
  508. When using ``kaiming_normal`` or ``kaiming_normal_`` for initialisation,
  509. ``nonlinearity='linear'`` should be used instead of ``nonlinearity='selu'``
  510. in order to get `Self-Normalizing Neural Networks`_.
  511. See :func:`torch.nn.init.calculate_gain` for more information.
  512. More details can be found in the paper `Self-Normalizing Neural Networks`_ .
  513. Args:
  514. inplace (bool, optional): can optionally do the operation in-place. Default: ``False``
  515. Shape:
  516. - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
  517. - Output: :math:`(*)`, same shape as the input.
  518. .. image:: ../scripts/activation_images/SELU.png
  519. Examples::
  520. >>> m = nn.SELU()
  521. >>> input = torch.randn(2)
  522. >>> output = m(input)
  523. .. _Self-Normalizing Neural Networks: https://arxiv.org/abs/1706.02515
  524. """
  525. __constants__ = ["inplace"]
  526. inplace: bool
  527. def __init__(self, inplace: bool = False) -> None:
  528. super().__init__()
  529. self.inplace = inplace
  530. def forward(self, input: Tensor) -> Tensor:
  531. """
  532. Runs the forward pass.
  533. """
  534. return F.selu(input, self.inplace)
  535. def extra_repr(self) -> str:
  536. """
  537. Return the extra representation of the module.
  538. """
  539. inplace_str = "inplace=True" if self.inplace else ""
  540. return inplace_str
  541. class GLU(Module):
  542. r"""Applies the gated linear unit function.
  543. :math:`{GLU}(a, b)= a \otimes \sigma(b)` where :math:`a` is the first half
  544. of the input matrices and :math:`b` is the second half.
  545. Args:
  546. dim (int): the dimension on which to split the input. Default: -1
  547. Shape:
  548. - Input: :math:`(\ast_1, N, \ast_2)` where `*` means, any number of additional
  549. dimensions
  550. - Output: :math:`(\ast_1, M, \ast_2)` where :math:`M=N/2`
  551. .. image:: ../scripts/activation_images/GLU.png
  552. Examples::
  553. >>> m = nn.GLU()
  554. >>> input = torch.randn(4, 2)
  555. >>> output = m(input)
  556. """
  557. __constants__ = ["dim"]
  558. dim: int
  559. def __init__(self, dim: int = -1) -> None:
  560. super().__init__()
  561. self.dim = dim
  562. def forward(self, input: Tensor) -> Tensor:
  563. """
  564. Runs the forward pass.
  565. """
  566. return F.glu(input, self.dim)
  567. def extra_repr(self) -> str:
  568. """
  569. Return the extra representation of the module.
  570. """
  571. return f"dim={self.dim}"
  572. class GELU(Module):
  573. r"""Applies the Gaussian Error Linear Units function.
  574. .. math:: \text{GELU}(x) = x * \Phi(x)
  575. where :math:`\Phi(x)` is the Cumulative Distribution Function for Gaussian Distribution.
  576. When the approximate argument is 'tanh', Gelu is estimated with:
  577. .. math:: \text{GELU}(x) = 0.5 * x * (1 + \text{Tanh}(\sqrt{2 / \pi} * (x + 0.044715 * x^3)))
  578. Args:
  579. approximate (str, optional): the gelu approximation algorithm to use:
  580. ``'none'`` | ``'tanh'``. Default: ``'none'``
  581. Shape:
  582. - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
  583. - Output: :math:`(*)`, same shape as the input.
  584. .. image:: ../scripts/activation_images/GELU.png
  585. Examples::
  586. >>> m = nn.GELU()
  587. >>> input = torch.randn(2)
  588. >>> output = m(input)
  589. """
  590. __constants__ = ["approximate"]
  591. approximate: str
  592. def __init__(self, approximate: str = "none") -> None:
  593. super().__init__()
  594. self.approximate = approximate
  595. def forward(self, input: Tensor) -> Tensor:
  596. """
  597. Runs the forward pass.
  598. """
  599. return F.gelu(input, approximate=self.approximate)
  600. def extra_repr(self) -> str:
  601. """
  602. Return the extra representation of the module.
  603. """
  604. return f"approximate={repr(self.approximate)}"
  605. class Hardshrink(Module):
  606. r"""Applies the Hard Shrinkage (Hardshrink) function element-wise.
  607. Hardshrink is defined as:
  608. .. math::
  609. \text{HardShrink}(x) =
  610. \begin{cases}
  611. x, & \text{ if } x > \lambda \\
  612. x, & \text{ if } x < -\lambda \\
  613. 0, & \text{ otherwise }
  614. \end{cases}
  615. Args:
  616. lambd: the :math:`\lambda` value for the Hardshrink formulation. Default: 0.5
  617. Shape:
  618. - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
  619. - Output: :math:`(*)`, same shape as the input.
  620. .. image:: ../scripts/activation_images/Hardshrink.png
  621. Examples::
  622. >>> m = nn.Hardshrink()
  623. >>> input = torch.randn(2)
  624. >>> output = m(input)
  625. """
  626. __constants__ = ["lambd"]
  627. lambd: float
  628. def __init__(self, lambd: float = 0.5) -> None:
  629. super().__init__()
  630. self.lambd = lambd
  631. def forward(self, input: Tensor) -> Tensor:
  632. """
  633. Run forward pass.
  634. """
  635. return F.hardshrink(input, self.lambd)
  636. def extra_repr(self) -> str:
  637. """
  638. Return the extra representation of the module.
  639. """
  640. return f"{self.lambd}"
  641. class LeakyReLU(Module):
  642. r"""Applies the LeakyReLU function element-wise.
  643. .. math::
  644. \text{LeakyReLU}(x) = \max(0, x) + \text{negative\_slope} * \min(0, x)
  645. or
  646. .. math::
  647. \text{LeakyReLU}(x) =
  648. \begin{cases}
  649. x, & \text{ if } x \geq 0 \\
  650. \text{negative\_slope} \times x, & \text{ otherwise }
  651. \end{cases}
  652. Args:
  653. negative_slope: Controls the angle of the negative slope (which is used for
  654. negative input values). Default: 1e-2
  655. inplace: can optionally do the operation in-place. Default: ``False``
  656. Shape:
  657. - Input: :math:`(*)` where `*` means, any number of additional
  658. dimensions
  659. - Output: :math:`(*)`, same shape as the input
  660. .. image:: ../scripts/activation_images/LeakyReLU.png
  661. Examples::
  662. >>> m = nn.LeakyReLU(0.1)
  663. >>> input = torch.randn(2)
  664. >>> output = m(input)
  665. """
  666. __constants__ = ["inplace", "negative_slope"]
  667. inplace: bool
  668. negative_slope: float
  669. def __init__(self, negative_slope: float = 1e-2, inplace: bool = False) -> None:
  670. super().__init__()
  671. self.negative_slope = negative_slope
  672. self.inplace = inplace
  673. def forward(self, input: Tensor) -> Tensor:
  674. """
  675. Run forward pass.
  676. """
  677. return F.leaky_relu(input, self.negative_slope, self.inplace)
  678. def extra_repr(self) -> str:
  679. """
  680. Return the extra representation of the module.
  681. """
  682. inplace_str = ", inplace=True" if self.inplace else ""
  683. return f"negative_slope={self.negative_slope}{inplace_str}"
  684. class LogSigmoid(Module):
  685. r"""Applies the Logsigmoid function element-wise.
  686. .. math::
  687. \text{LogSigmoid}(x) = \log\left(\frac{ 1 }{ 1 + \exp(-x)}\right)
  688. Shape:
  689. - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
  690. - Output: :math:`(*)`, same shape as the input.
  691. .. image:: ../scripts/activation_images/LogSigmoid.png
  692. Examples::
  693. >>> m = nn.LogSigmoid()
  694. >>> input = torch.randn(2)
  695. >>> output = m(input)
  696. """
  697. def forward(self, input: Tensor) -> Tensor:
  698. """
  699. Run forward pass.
  700. """
  701. return F.logsigmoid(input)
  702. class Softplus(Module):
  703. r"""Applies the Softplus function element-wise.
  704. .. math::
  705. \text{Softplus}(x) = \frac{1}{\beta} * \log(1 + \exp(\beta * x))
  706. SoftPlus is a smooth approximation to the ReLU function and can be used
  707. to constrain the output of a machine to always be positive.
  708. For numerical stability the implementation reverts to the linear function
  709. when :math:`input \times \beta > threshold`.
  710. Args:
  711. beta: the :math:`\beta` value for the Softplus formulation. Default: 1
  712. threshold: values above this revert to a linear function. Default: 20
  713. Shape:
  714. - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
  715. - Output: :math:`(*)`, same shape as the input.
  716. .. image:: ../scripts/activation_images/Softplus.png
  717. Examples::
  718. >>> m = nn.Softplus()
  719. >>> input = torch.randn(2)
  720. >>> output = m(input)
  721. """
  722. __constants__ = ["beta", "threshold"]
  723. beta: float
  724. threshold: float
  725. def __init__(self, beta: float = 1.0, threshold: float = 20.0) -> None:
  726. super().__init__()
  727. self.beta = beta
  728. self.threshold = threshold
  729. def forward(self, input: Tensor) -> Tensor:
  730. """
  731. Run forward pass.
  732. """
  733. return F.softplus(input, self.beta, self.threshold)
  734. def extra_repr(self) -> str:
  735. """
  736. Return the extra representation of the module.
  737. """
  738. return f"beta={self.beta}, threshold={self.threshold}"
  739. class Softshrink(Module):
  740. r"""Applies the soft shrinkage function element-wise.
  741. .. math::
  742. \text{SoftShrinkage}(x) =
  743. \begin{cases}
  744. x - \lambda, & \text{ if } x > \lambda \\
  745. x + \lambda, & \text{ if } x < -\lambda \\
  746. 0, & \text{ otherwise }
  747. \end{cases}
  748. Args:
  749. lambd: the :math:`\lambda` (must be no less than zero) value for the Softshrink formulation. Default: 0.5
  750. Shape:
  751. - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
  752. - Output: :math:`(*)`, same shape as the input.
  753. .. image:: ../scripts/activation_images/Softshrink.png
  754. Examples::
  755. >>> m = nn.Softshrink()
  756. >>> input = torch.randn(2)
  757. >>> output = m(input)
  758. """
  759. __constants__ = ["lambd"]
  760. lambd: float
  761. def __init__(self, lambd: float = 0.5) -> None:
  762. super().__init__()
  763. self.lambd = lambd
  764. def forward(self, input: Tensor) -> Tensor:
  765. """
  766. Run forward pass.
  767. """
  768. return F.softshrink(input, self.lambd)
  769. def extra_repr(self) -> str:
  770. """
  771. Return the extra representation of the module.
  772. """
  773. return str(self.lambd)
  774. def _check_arg_device(x: Optional[torch.Tensor]) -> bool:
  775. if x is not None:
  776. return x.device.type in [
  777. "cpu",
  778. "cuda",
  779. torch.utils.backend_registration._privateuse1_backend_name,
  780. ]
  781. return True
  782. def _arg_requires_grad(x: Optional[torch.Tensor]) -> bool:
  783. if x is not None:
  784. return x.requires_grad
  785. return False
  786. def _is_make_fx_tracing():
  787. if not torch.jit.is_scripting():
  788. torch_dispatch_mode_stack = (
  789. torch.utils._python_dispatch._get_current_dispatch_mode_stack()
  790. )
  791. return any(
  792. type(x) == torch.fx.experimental.proxy_tensor.ProxyTorchDispatchMode
  793. for x in torch_dispatch_mode_stack
  794. )
  795. else:
  796. return False
  797. class MultiheadAttention(Module):
  798. r"""Allows the model to jointly attend to information from different representation subspaces.
  799. This MultiheadAttention layer implements the original architecture described
  800. in the `Attention Is All You Need <https://arxiv.org/abs/1706.03762>`_ paper. The
  801. intent of this layer is as a reference implementation for foundational understanding
  802. and thus it contains only limited features relative to newer architectures.
  803. Given the fast pace of innovation in transformer-like architectures, we recommend
  804. exploring this `tutorial <https://pytorch.org/tutorials/intermediate/transformer_building_blocks.html>`_
  805. to build efficient layers from building blocks in core or using higher
  806. level libraries from the `PyTorch Ecosystem <https://landscape.pytorch.org/>`_.
  807. Multi-Head Attention is defined as:
  808. .. math::
  809. \text{MultiHead}(Q, K, V) = \text{Concat}(\text{head}_1,\dots,\text{head}_h)W^O
  810. where :math:`\text{head}_i = \text{Attention}(QW_i^Q, KW_i^K, VW_i^V)`.
  811. ``nn.MultiheadAttention`` will use the optimized implementations of
  812. ``scaled_dot_product_attention()`` when possible.
  813. In addition to support for the new ``scaled_dot_product_attention()``
  814. function, for speeding up Inference, MHA will use
  815. fastpath inference with support for Nested Tensors, iff:
  816. - self attention is being computed (i.e., ``query``, ``key``, and ``value`` are the same tensor).
  817. - inputs are batched (3D) with ``batch_first==True``
  818. - Either autograd is disabled (using ``torch.inference_mode`` or ``torch.no_grad``) or no tensor argument ``requires_grad``
  819. - training is disabled (using ``.eval()``)
  820. - ``add_bias_kv`` is ``False``
  821. - ``add_zero_attn`` is ``False``
  822. - ``kdim`` and ``vdim`` are equal to ``embed_dim``
  823. - if a `NestedTensor <https://pytorch.org/docs/stable/nested.html>`_ is passed, neither ``key_padding_mask``
  824. nor ``attn_mask`` is passed
  825. - autocast is disabled
  826. If the optimized inference fastpath implementation is in use, a
  827. `NestedTensor <https://pytorch.org/docs/stable/nested.html>`_ can be passed for
  828. ``query``/``key``/``value`` to represent padding more efficiently than using a
  829. padding mask. In this case, a `NestedTensor <https://pytorch.org/docs/stable/nested.html>`_
  830. will be returned, and an additional speedup proportional to the fraction of the input
  831. that is padding can be expected.
  832. Args:
  833. embed_dim: Total dimension of the model.
  834. num_heads: Number of parallel attention heads. Note that ``embed_dim`` will be split
  835. across ``num_heads`` (i.e. each head will have dimension ``embed_dim // num_heads``).
  836. dropout: Dropout probability on ``attn_output_weights``. Default: ``0.0`` (no dropout).
  837. bias: If specified, adds bias to input / output projection layers. Default: ``True``.
  838. add_bias_kv: If specified, adds bias to the key and value sequences at dim=0. Default: ``False``.
  839. add_zero_attn: If specified, adds a new batch of zeros to the key and value sequences at dim=1.
  840. Default: ``False``.
  841. kdim: Total number of features for keys. Default: ``None`` (uses ``kdim=embed_dim``).
  842. vdim: Total number of features for values. Default: ``None`` (uses ``vdim=embed_dim``).
  843. batch_first: If ``True``, then the input and output tensors are provided
  844. as (batch, seq, feature). Default: ``False`` (seq, batch, feature).
  845. Examples::
  846. >>> # xdoctest: +SKIP
  847. >>> multihead_attn = nn.MultiheadAttention(embed_dim, num_heads)
  848. >>> attn_output, attn_output_weights = multihead_attn(query, key, value)
  849. .. _`FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness`:
  850. https://arxiv.org/abs/2205.14135
  851. """
  852. __constants__ = ["batch_first"]
  853. bias_k: Optional[torch.Tensor]
  854. bias_v: Optional[torch.Tensor]
  855. def __init__(
  856. self,
  857. embed_dim,
  858. num_heads,
  859. dropout=0.0,
  860. bias=True,
  861. add_bias_kv=False,
  862. add_zero_attn=False,
  863. kdim=None,
  864. vdim=None,
  865. batch_first=False,
  866. device=None,
  867. dtype=None,
  868. ) -> None:
  869. if embed_dim <= 0 or num_heads <= 0:
  870. raise ValueError(
  871. f"embed_dim and num_heads must be greater than 0,"
  872. f" got embed_dim={embed_dim} and num_heads={num_heads} instead"
  873. )
  874. factory_kwargs = {"device": device, "dtype": dtype}
  875. super().__init__()
  876. self.embed_dim = embed_dim
  877. self.kdim = kdim if kdim is not None else embed_dim
  878. self.vdim = vdim if vdim is not None else embed_dim
  879. self._qkv_same_embed_dim = self.kdim == embed_dim and self.vdim == embed_dim
  880. self.num_heads = num_heads
  881. self.dropout = dropout
  882. self.batch_first = batch_first
  883. self.head_dim = embed_dim // num_heads
  884. assert self.head_dim * num_heads == self.embed_dim, (
  885. "embed_dim must be divisible by num_heads"
  886. )
  887. if not self._qkv_same_embed_dim:
  888. self.q_proj_weight = Parameter(
  889. torch.empty((embed_dim, embed_dim), **factory_kwargs)
  890. )
  891. self.k_proj_weight = Parameter(
  892. torch.empty((embed_dim, self.kdim), **factory_kwargs)
  893. )
  894. self.v_proj_weight = Parameter(
  895. torch.empty((embed_dim, self.vdim), **factory_kwargs)
  896. )
  897. self.register_parameter("in_proj_weight", None)
  898. else:
  899. self.in_proj_weight = Parameter(
  900. torch.empty((3 * embed_dim, embed_dim), **factory_kwargs)
  901. )
  902. self.register_parameter("q_proj_weight", None)
  903. self.register_parameter("k_proj_weight", None)
  904. self.register_parameter("v_proj_weight", None)
  905. if bias:
  906. self.in_proj_bias = Parameter(torch.empty(3 * embed_dim, **factory_kwargs))
  907. else:
  908. self.register_parameter("in_proj_bias", None)
  909. self.out_proj = NonDynamicallyQuantizableLinear(
  910. embed_dim, embed_dim, bias=bias, **factory_kwargs
  911. )
  912. if add_bias_kv:
  913. self.bias_k = Parameter(torch.empty((1, 1, embed_dim), **factory_kwargs))
  914. self.bias_v = Parameter(torch.empty((1, 1, embed_dim), **factory_kwargs))
  915. else:
  916. self.bias_k = self.bias_v = None
  917. self.add_zero_attn = add_zero_attn
  918. self._reset_parameters()
  919. def _reset_parameters(self) -> None:
  920. if self._qkv_same_embed_dim:
  921. xavier_uniform_(self.in_proj_weight)
  922. else:
  923. xavier_uniform_(self.q_proj_weight)
  924. xavier_uniform_(self.k_proj_weight)
  925. xavier_uniform_(self.v_proj_weight)
  926. if self.in_proj_bias is not None:
  927. constant_(self.in_proj_bias, 0.0)
  928. constant_(self.out_proj.bias, 0.0)
  929. if self.bias_k is not None:
  930. xavier_normal_(self.bias_k)
  931. if self.bias_v is not None:
  932. xavier_normal_(self.bias_v)
  933. def __setstate__(self, state):
  934. # Support loading old MultiheadAttention checkpoints generated by v1.1.0
  935. if "_qkv_same_embed_dim" not in state:
  936. state["_qkv_same_embed_dim"] = True
  937. super().__setstate__(state)
  938. def forward(
  939. self,
  940. query: Tensor,
  941. key: Tensor,
  942. value: Tensor,
  943. key_padding_mask: Optional[Tensor] = None,
  944. need_weights: bool = True,
  945. attn_mask: Optional[Tensor] = None,
  946. average_attn_weights: bool = True,
  947. is_causal: bool = False,
  948. ) -> tuple[Tensor, Optional[Tensor]]:
  949. r"""Compute attention outputs using query, key, and value embeddings.
  950. Supports optional parameters for padding, masks and attention weights.
  951. Args:
  952. query: Query embeddings of shape :math:`(L, E_q)` for unbatched input, :math:`(L, N, E_q)` when ``batch_first=False``
  953. or :math:`(N, L, E_q)` when ``batch_first=True``, where :math:`L` is the target sequence length,
  954. :math:`N` is the batch size, and :math:`E_q` is the query embedding dimension ``embed_dim``.
  955. Queries are compared against key-value pairs to produce the output.
  956. See "Attention Is All You Need" for more details.
  957. key: Key embeddings of shape :math:`(S, E_k)` for unbatched input, :math:`(S, N, E_k)` when ``batch_first=False``
  958. or :math:`(N, S, E_k)` when ``batch_first=True``, where :math:`S` is the source sequence length,
  959. :math:`N` is the batch size, and :math:`E_k` is the key embedding dimension ``kdim``.
  960. See "Attention Is All You Need" for more details.
  961. value: Value embeddings of shape :math:`(S, E_v)` for unbatched input, :math:`(S, N, E_v)` when
  962. ``batch_first=False`` or :math:`(N, S, E_v)` when ``batch_first=True``, where :math:`S` is the source
  963. sequence length, :math:`N` is the batch size, and :math:`E_v` is the value embedding dimension ``vdim``.
  964. See "Attention Is All You Need" for more details.
  965. key_padding_mask: If specified, a mask of shape :math:`(N, S)` indicating which elements within ``key``
  966. to ignore for the purpose of attention (i.e. treat as "padding"). For unbatched `query`, shape should be :math:`(S)`.
  967. Binary and float masks are supported.
  968. For a binary mask, a ``True`` value indicates that the corresponding ``key`` value will be ignored for
  969. the purpose of attention. For a float mask, it will be directly added to the corresponding ``key`` value.
  970. need_weights: If specified, returns ``attn_output_weights`` in addition to ``attn_outputs``.
  971. Set ``need_weights=False`` to use the optimized ``scaled_dot_product_attention``
  972. and achieve the best performance for MHA.
  973. Default: ``True``.
  974. attn_mask: If specified, a 2D or 3D mask preventing attention to certain positions. Must be of shape
  975. :math:`(L, S)` or :math:`(N\cdot\text{num\_heads}, L, S)`, where :math:`N` is the batch size,
  976. :math:`L` is the target sequence length, and :math:`S` is the source sequence length. A 2D mask will be
  977. broadcasted across the batch while a 3D mask allows for a different mask for each entry in the batch.
  978. Binary and float masks are supported. For a binary mask, a ``True`` value indicates that the
  979. corresponding position is not allowed to attend. For a float mask, the mask values will be added to
  980. the attention weight.
  981. If both attn_mask and key_padding_mask are supplied, their types should match.
  982. average_attn_weights: If true, indicates that the returned ``attn_weights`` should be averaged across
  983. heads. Otherwise, ``attn_weights`` are provided separately per head. Note that this flag only has an
  984. effect when ``need_weights=True``. Default: ``True`` (i.e. average weights across heads)
  985. is_causal: If specified, applies a causal mask as attention mask.
  986. Default: ``False``.
  987. Warning:
  988. ``is_causal`` provides a hint that ``attn_mask`` is the
  989. causal mask. Providing incorrect hints can result in
  990. incorrect execution, including forward and backward
  991. compatibility.
  992. Outputs:
  993. - **attn_output** - Attention outputs of shape :math:`(L, E)` when input is unbatched,
  994. :math:`(L, N, E)` when ``batch_first=False`` or :math:`(N, L, E)` when ``batch_first=True``,
  995. where :math:`L` is the target sequence length, :math:`N` is the batch size, and :math:`E` is the
  996. embedding dimension ``embed_dim``.
  997. - **attn_output_weights** - Only returned when ``need_weights=True``. If ``average_attn_weights=True``,
  998. returns attention weights averaged across heads of shape :math:`(L, S)` when input is unbatched or
  999. :math:`(N, L, S)`, where :math:`N` is the batch size, :math:`L` is the target sequence length, and
  1000. :math:`S` is the source sequence length. If ``average_attn_weights=False``, returns attention weights per
  1001. head of shape :math:`(\text{num\_heads}, L, S)` when input is unbatched or :math:`(N, \text{num\_heads}, L, S)`.
  1002. .. note::
  1003. `batch_first` argument is ignored for unbatched inputs.
  1004. """ # noqa: B950
  1005. why_not_fast_path = ""
  1006. if (
  1007. (attn_mask is not None and torch.is_floating_point(attn_mask))
  1008. or (key_padding_mask is not None)
  1009. and torch.is_floating_point(key_padding_mask)
  1010. ):
  1011. why_not_fast_path = "floating-point masks are not supported for fast path."
  1012. is_batched = query.dim() == 3
  1013. key_padding_mask = F._canonical_mask(
  1014. mask=key_padding_mask,
  1015. mask_name="key_padding_mask",
  1016. other_type=F._none_or_dtype(attn_mask),
  1017. other_name="attn_mask",
  1018. target_type=query.dtype,
  1019. )
  1020. attn_mask = F._canonical_mask(
  1021. mask=attn_mask,
  1022. mask_name="attn_mask",
  1023. other_type=None,
  1024. other_name="",
  1025. target_type=query.dtype,
  1026. check_other=False,
  1027. )
  1028. is_fastpath_enabled = torch.backends.mha.get_fastpath_enabled()
  1029. if not is_fastpath_enabled:
  1030. why_not_fast_path = "torch.backends.mha.get_fastpath_enabled() was not True"
  1031. elif not is_batched:
  1032. why_not_fast_path = (
  1033. f"input not batched; expected query.dim() of 3 but got {query.dim()}"
  1034. )
  1035. elif query is not key or key is not value:
  1036. # When lifting this restriction, don't forget to either
  1037. # enforce that the dtypes all match or test cases where
  1038. # they don't!
  1039. why_not_fast_path = "non-self attention was used (query, key, and value are not the same Tensor)"
  1040. elif self.in_proj_bias is not None and query.dtype != self.in_proj_bias.dtype:
  1041. why_not_fast_path = f"dtypes of query ({query.dtype}) and self.in_proj_bias ({self.in_proj_bias.dtype}) don't match"
  1042. elif self.in_proj_weight is None:
  1043. why_not_fast_path = "in_proj_weight was None"
  1044. elif query.dtype != self.in_proj_weight.dtype:
  1045. # this case will fail anyway, but at least they'll get a useful error message.
  1046. why_not_fast_path = f"dtypes of query ({query.dtype}) and self.in_proj_weight ({self.in_proj_weight.dtype}) don't match"
  1047. elif self.training:
  1048. why_not_fast_path = "training is enabled"
  1049. elif (self.num_heads % 2) != 0:
  1050. why_not_fast_path = "self.num_heads is not even"
  1051. elif not self.batch_first:
  1052. why_not_fast_path = "batch_first was not True"
  1053. elif self.bias_k is not None:
  1054. why_not_fast_path = "self.bias_k was not None"
  1055. elif self.bias_v is not None:
  1056. why_not_fast_path = "self.bias_v was not None"
  1057. elif self.add_zero_attn:
  1058. why_not_fast_path = "add_zero_attn was enabled"
  1059. elif not self._qkv_same_embed_dim:
  1060. why_not_fast_path = "_qkv_same_embed_dim was not True"
  1061. elif query.is_nested and (
  1062. key_padding_mask is not None or attn_mask is not None
  1063. ):
  1064. why_not_fast_path = (
  1065. "supplying both src_key_padding_mask and src_mask at the same time \
  1066. is not supported with NestedTensor input"
  1067. )
  1068. elif torch.is_autocast_enabled():
  1069. why_not_fast_path = "autocast is enabled"
  1070. if not why_not_fast_path:
  1071. tensor_args = (
  1072. query,
  1073. key,
  1074. value,
  1075. self.in_proj_weight,
  1076. self.in_proj_bias,
  1077. self.out_proj.weight,
  1078. self.out_proj.bias,
  1079. )
  1080. # We have to use list comprehensions below because TorchScript does not support
  1081. # generator expressions.
  1082. if torch.overrides.has_torch_function(tensor_args):
  1083. why_not_fast_path = "some Tensor argument has_torch_function"
  1084. elif _is_make_fx_tracing():
  1085. why_not_fast_path = "we are running make_fx tracing"
  1086. elif not all(_check_arg_device(x) for x in tensor_args):
  1087. why_not_fast_path = (
  1088. "some Tensor argument's device is neither one of "
  1089. f"cpu, cuda or {torch.utils.backend_registration._privateuse1_backend_name}"
  1090. )
  1091. elif torch.is_grad_enabled() and any(
  1092. _arg_requires_grad(x) for x in tensor_args
  1093. ):
  1094. why_not_fast_path = (
  1095. "grad is enabled and at least one of query or the "
  1096. "input/output projection weights or biases requires_grad"
  1097. )
  1098. if not why_not_fast_path:
  1099. merged_mask, mask_type = self.merge_masks(
  1100. attn_mask, key_padding_mask, query
  1101. )
  1102. if self.in_proj_bias is not None and self.in_proj_weight is not None:
  1103. return torch._native_multi_head_attention(
  1104. query,
  1105. key,
  1106. value,
  1107. self.embed_dim,
  1108. self.num_heads,
  1109. self.in_proj_weight,
  1110. self.in_proj_bias,
  1111. self.out_proj.weight,
  1112. self.out_proj.bias,
  1113. merged_mask,
  1114. need_weights,
  1115. average_attn_weights,
  1116. mask_type,
  1117. )
  1118. any_nested = query.is_nested or key.is_nested or value.is_nested
  1119. assert not any_nested, (
  1120. "MultiheadAttention does not support NestedTensor outside of its fast path. "
  1121. + f"The fast path was not hit because {why_not_fast_path}"
  1122. )
  1123. if self.batch_first and is_batched:
  1124. # make sure that the transpose op does not affect the "is" property
  1125. if key is value:
  1126. if query is key:
  1127. query = key = value = query.transpose(1, 0)
  1128. else:
  1129. query, key = (x.transpose(1, 0) for x in (query, key))
  1130. value = key
  1131. else:
  1132. query, key, value = (x.transpose(1, 0) for x in (query, key, value))
  1133. if not self._qkv_same_embed_dim:
  1134. attn_output, attn_output_weights = F.multi_head_attention_forward(
  1135. query,
  1136. key,
  1137. value,
  1138. self.embed_dim,
  1139. self.num_heads,
  1140. self.in_proj_weight,
  1141. self.in_proj_bias,
  1142. self.bias_k,
  1143. self.bias_v,
  1144. self.add_zero_attn,
  1145. self.dropout,
  1146. self.out_proj.weight,
  1147. self.out_proj.bias,
  1148. training=self.training,
  1149. key_padding_mask=key_padding_mask,
  1150. need_weights=need_weights,
  1151. attn_mask=attn_mask,
  1152. use_separate_proj_weight=True,
  1153. q_proj_weight=self.q_proj_weight,
  1154. k_proj_weight=self.k_proj_weight,
  1155. v_proj_weight=self.v_proj_weight,
  1156. average_attn_weights=average_attn_weights,
  1157. is_causal=is_causal,
  1158. )
  1159. else:
  1160. attn_output, attn_output_weights = F.multi_head_attention_forward(
  1161. query,
  1162. key,
  1163. value,
  1164. self.embed_dim,
  1165. self.num_heads,
  1166. self.in_proj_weight,
  1167. self.in_proj_bias,
  1168. self.bias_k,
  1169. self.bias_v,
  1170. self.add_zero_attn,
  1171. self.dropout,
  1172. self.out_proj.weight,
  1173. self.out_proj.bias,
  1174. training=self.training,
  1175. key_padding_mask=key_padding_mask,
  1176. need_weights=need_weights,
  1177. attn_mask=attn_mask,
  1178. average_attn_weights=average_attn_weights,
  1179. is_causal=is_causal,
  1180. )
  1181. if self.batch_first and is_batched:
  1182. return attn_output.transpose(1, 0), attn_output_weights
  1183. else:
  1184. return attn_output, attn_output_weights
  1185. def merge_masks(
  1186. self,
  1187. attn_mask: Optional[Tensor],
  1188. key_padding_mask: Optional[Tensor],
  1189. query: Tensor,
  1190. ) -> tuple[Optional[Tensor], Optional[int]]:
  1191. r"""Determine mask type and combine masks if necessary.
  1192. If only one mask is provided, that mask
  1193. and the corresponding mask type will be returned. If both masks are provided, they will be both
  1194. expanded to shape ``(batch_size, num_heads, seq_len, seq_len)``, combined with logical ``or``
  1195. and mask type 2 will be returned
  1196. Args:
  1197. attn_mask: attention mask of shape ``(seq_len, seq_len)``, mask type 0
  1198. key_padding_mask: padding mask of shape ``(batch_size, seq_len)``, mask type 1
  1199. query: query embeddings of shape ``(batch_size, seq_len, embed_dim)``
  1200. Returns:
  1201. merged_mask: merged mask
  1202. mask_type: merged mask type (0, 1, or 2)
  1203. """
  1204. mask_type: Optional[int] = None
  1205. merged_mask: Optional[Tensor] = None
  1206. if key_padding_mask is not None:
  1207. mask_type = 1
  1208. merged_mask = key_padding_mask
  1209. if attn_mask is not None:
  1210. # In this branch query can't be a nested tensor, so it has a shape
  1211. batch_size, seq_len, _ = query.shape
  1212. mask_type = 2
  1213. # Always expands attn_mask to 4D
  1214. if attn_mask.dim() == 3:
  1215. attn_mask_expanded = attn_mask.view(batch_size, -1, seq_len, seq_len)
  1216. else: # attn_mask.dim() == 2:
  1217. attn_mask_expanded = attn_mask.view(1, 1, seq_len, seq_len).expand(
  1218. batch_size, self.num_heads, -1, -1
  1219. )
  1220. merged_mask = attn_mask_expanded
  1221. if key_padding_mask is not None:
  1222. key_padding_mask_expanded = key_padding_mask.view(
  1223. batch_size, 1, 1, seq_len
  1224. ).expand(-1, self.num_heads, -1, -1)
  1225. merged_mask = attn_mask_expanded + key_padding_mask_expanded
  1226. # no attn_mask and no key_padding_mask, returns None, None
  1227. return merged_mask, mask_type
  1228. class PReLU(Module):
  1229. r"""Applies the element-wise PReLU function.
  1230. .. math::
  1231. \text{PReLU}(x) = \max(0,x) + a * \min(0,x)
  1232. or
  1233. .. math::
  1234. \text{PReLU}(x) =
  1235. \begin{cases}
  1236. x, & \text{ if } x \ge 0 \\
  1237. ax, & \text{ otherwise }
  1238. \end{cases}
  1239. Here :math:`a` is a learnable parameter. When called without arguments, `nn.PReLU()` uses a single
  1240. parameter :math:`a` across all input channels. If called with `nn.PReLU(nChannels)`,
  1241. a separate :math:`a` is used for each input channel.
  1242. .. note::
  1243. weight decay should not be used when learning :math:`a` for good performance.
  1244. .. note::
  1245. Channel dim is the 2nd dim of input. When input has dims < 2, then there is
  1246. no channel dim and the number of channels = 1.
  1247. Args:
  1248. num_parameters (int): number of :math:`a` to learn.
  1249. Although it takes an int as input, there is only two values are legitimate:
  1250. 1, or the number of channels at input. Default: 1
  1251. init (float): the initial value of :math:`a`. Default: 0.25
  1252. Shape:
  1253. - Input: :math:`( *)` where `*` means, any number of additional
  1254. dimensions.
  1255. - Output: :math:`(*)`, same shape as the input.
  1256. Attributes:
  1257. weight (Tensor): the learnable weights of shape (:attr:`num_parameters`).
  1258. .. image:: ../scripts/activation_images/PReLU.png
  1259. Examples::
  1260. >>> m = nn.PReLU()
  1261. >>> input = torch.randn(2)
  1262. >>> output = m(input)
  1263. """
  1264. __constants__ = ["num_parameters"]
  1265. num_parameters: int
  1266. def __init__(
  1267. self, num_parameters: int = 1, init: float = 0.25, device=None, dtype=None
  1268. ) -> None:
  1269. factory_kwargs = {"device": device, "dtype": dtype}
  1270. self.num_parameters = num_parameters
  1271. super().__init__()
  1272. self.init = init
  1273. self.weight = Parameter(torch.empty(num_parameters, **factory_kwargs))
  1274. self.reset_parameters()
  1275. def reset_parameters(self) -> None:
  1276. """
  1277. Resets parameters based on their initialization used in ``__init__``.
  1278. """
  1279. torch.nn.init.constant_(self.weight, self.init)
  1280. def forward(self, input: Tensor) -> Tensor:
  1281. """
  1282. Runs the forward pass.
  1283. """
  1284. return F.prelu(input, self.weight)
  1285. def extra_repr(self) -> str:
  1286. """
  1287. Return the extra representation of the module.
  1288. """
  1289. return f"num_parameters={self.num_parameters}"
  1290. class Softsign(Module):
  1291. r"""Applies the element-wise Softsign function.
  1292. .. math::
  1293. \text{SoftSign}(x) = \frac{x}{ 1 + |x|}
  1294. Shape:
  1295. - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
  1296. - Output: :math:`(*)`, same shape as the input.
  1297. .. image:: ../scripts/activation_images/Softsign.png
  1298. Examples::
  1299. >>> m = nn.Softsign()
  1300. >>> input = torch.randn(2)
  1301. >>> output = m(input)
  1302. """
  1303. def forward(self, input: Tensor) -> Tensor:
  1304. """
  1305. Runs the forward pass.
  1306. """
  1307. return F.softsign(input)
  1308. class Tanhshrink(Module):
  1309. r"""Applies the element-wise Tanhshrink function.
  1310. .. math::
  1311. \text{Tanhshrink}(x) = x - \tanh(x)
  1312. Shape:
  1313. - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
  1314. - Output: :math:`(*)`, same shape as the input.
  1315. .. image:: ../scripts/activation_images/Tanhshrink.png
  1316. Examples::
  1317. >>> m = nn.Tanhshrink()
  1318. >>> input = torch.randn(2)
  1319. >>> output = m(input)
  1320. """
  1321. def forward(self, input: Tensor) -> Tensor:
  1322. """
  1323. Runs the forward pass.
  1324. """
  1325. return F.tanhshrink(input)
  1326. class Softmin(Module):
  1327. r"""Applies the Softmin function to an n-dimensional input Tensor.
  1328. Rescales them so that the elements of the n-dimensional output Tensor
  1329. lie in the range `[0, 1]` and sum to 1.
  1330. Softmin is defined as:
  1331. .. math::
  1332. \text{Softmin}(x_{i}) = \frac{\exp(-x_i)}{\sum_j \exp(-x_j)}
  1333. Shape:
  1334. - Input: :math:`(*)` where `*` means, any number of additional
  1335. dimensions
  1336. - Output: :math:`(*)`, same shape as the input
  1337. Args:
  1338. dim (int): A dimension along which Softmin will be computed (so every slice
  1339. along dim will sum to 1).
  1340. Returns:
  1341. a Tensor of the same dimension and shape as the input, with
  1342. values in the range [0, 1]
  1343. Examples::
  1344. >>> m = nn.Softmin(dim=1)
  1345. >>> input = torch.randn(2, 3)
  1346. >>> output = m(input)
  1347. """
  1348. __constants__ = ["dim"]
  1349. dim: Optional[int]
  1350. def __init__(self, dim: Optional[int] = None) -> None:
  1351. super().__init__()
  1352. self.dim = dim
  1353. def __setstate__(self, state):
  1354. super().__setstate__(state)
  1355. if not hasattr(self, "dim"):
  1356. self.dim = None
  1357. def forward(self, input: Tensor) -> Tensor:
  1358. """
  1359. Runs the forward pass.
  1360. """
  1361. return F.softmin(input, self.dim, _stacklevel=5)
  1362. def extra_repr(self) -> str:
  1363. """
  1364. Return the extra representation of the module.
  1365. """
  1366. return f"dim={self.dim}"
  1367. class Softmax(Module):
  1368. r"""Applies the Softmax function to an n-dimensional input Tensor.
  1369. Rescales them so that the elements of the n-dimensional output Tensor
  1370. lie in the range [0,1] and sum to 1.
  1371. Softmax is defined as:
  1372. .. math::
  1373. \text{Softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}
  1374. When the input Tensor is a sparse tensor then the unspecified
  1375. values are treated as ``-inf``.
  1376. Shape:
  1377. - Input: :math:`(*)` where `*` means, any number of additional
  1378. dimensions
  1379. - Output: :math:`(*)`, same shape as the input
  1380. Returns:
  1381. a Tensor of the same dimension and shape as the input with
  1382. values in the range [0, 1]
  1383. Args:
  1384. dim (int): A dimension along which Softmax will be computed (so every slice
  1385. along dim will sum to 1).
  1386. .. note::
  1387. This module doesn't work directly with NLLLoss,
  1388. which expects the Log to be computed between the Softmax and itself.
  1389. Use `LogSoftmax` instead (it's faster and has better numerical properties).
  1390. Examples::
  1391. >>> m = nn.Softmax(dim=1)
  1392. >>> input = torch.randn(2, 3)
  1393. >>> output = m(input)
  1394. """
  1395. __constants__ = ["dim"]
  1396. dim: Optional[int]
  1397. def __init__(self, dim: Optional[int] = None) -> None:
  1398. super().__init__()
  1399. self.dim = dim
  1400. def __setstate__(self, state):
  1401. super().__setstate__(state)
  1402. if not hasattr(self, "dim"):
  1403. self.dim = None
  1404. def forward(self, input: Tensor) -> Tensor:
  1405. """
  1406. Runs the forward pass.
  1407. """
  1408. return F.softmax(input, self.dim, _stacklevel=5)
  1409. def extra_repr(self) -> str:
  1410. """
  1411. Return the extra representation of the module.
  1412. """
  1413. return f"dim={self.dim}"
  1414. class Softmax2d(Module):
  1415. r"""Applies SoftMax over features to each spatial location.
  1416. When given an image of ``Channels x Height x Width``, it will
  1417. apply `Softmax` to each location :math:`(Channels, h_i, w_j)`
  1418. Shape:
  1419. - Input: :math:`(N, C, H, W)` or :math:`(C, H, W)`.
  1420. - Output: :math:`(N, C, H, W)` or :math:`(C, H, W)` (same shape as input)
  1421. Returns:
  1422. a Tensor of the same dimension and shape as the input with
  1423. values in the range [0, 1]
  1424. Examples::
  1425. >>> m = nn.Softmax2d()
  1426. >>> # you softmax over the 2nd dimension
  1427. >>> input = torch.randn(2, 3, 12, 13)
  1428. >>> output = m(input)
  1429. """
  1430. def forward(self, input: Tensor) -> Tensor:
  1431. """
  1432. Runs the forward pass.
  1433. """
  1434. if input.dim() not in (3, 4):
  1435. raise ValueError(
  1436. f"Softmax2d: expected input to be 3D or 4D, got {input.dim()}D instead"
  1437. )
  1438. return F.softmax(input, -3, _stacklevel=5)
  1439. class LogSoftmax(Module):
  1440. r"""Applies the :math:`\log(\text{Softmax}(x))` function to an n-dimensional input Tensor.
  1441. The LogSoftmax formulation can be simplified as:
  1442. .. math::
  1443. \text{LogSoftmax}(x_{i}) = \log\left(\frac{\exp(x_i) }{ \sum_j \exp(x_j)} \right)
  1444. Shape:
  1445. - Input: :math:`(*)` where `*` means, any number of additional
  1446. dimensions
  1447. - Output: :math:`(*)`, same shape as the input
  1448. Args:
  1449. dim (int): A dimension along which LogSoftmax will be computed.
  1450. Returns:
  1451. a Tensor of the same dimension and shape as the input with
  1452. values in the range [-inf, 0)
  1453. Examples::
  1454. >>> m = nn.LogSoftmax(dim=1)
  1455. >>> input = torch.randn(2, 3)
  1456. >>> output = m(input)
  1457. """
  1458. __constants__ = ["dim"]
  1459. dim: Optional[int]
  1460. def __init__(self, dim: Optional[int] = None) -> None:
  1461. super().__init__()
  1462. self.dim = dim
  1463. def __setstate__(self, state):
  1464. super().__setstate__(state)
  1465. if not hasattr(self, "dim"):
  1466. self.dim = None
  1467. def forward(self, input: Tensor) -> Tensor:
  1468. """
  1469. Runs the forward pass.
  1470. """
  1471. return F.log_softmax(input, self.dim, _stacklevel=5)
  1472. def extra_repr(self) -> str:
  1473. """
  1474. Return the extra representation of the module.
  1475. """
  1476. return f"dim={self.dim}"