a
    ßñh(›  ã                   @   sD  d dl Z d dlmZmZ d dlZd dlmZ ddlmZ d dlm	Z	 d dlm
Z
 d dlmZ d d	lmZ dd
lmZ ddlmZ G dd„ deƒZG dd„ deƒZG dd„ deƒZG dd„ deƒZG dd„ deƒZG dd„ deƒZG dd„ deƒZG dd„ deƒZG dd„ deƒZG dd „ d eƒZG d!d"„ d"eƒZG d#d$„ d$eƒZG d%d&„ d&eƒZG d'd(„ d(eƒZ G d)d*„ d*eƒZ!G d+d,„ d,eƒZ"G d-d.„ d.eƒZ#G d/d0„ d0eƒZ$G d1d2„ d2eƒZ%G d3d4„ d4eƒZ&G d5d6„ d6eƒZ'G d7d8„ d8eƒZ(G d9d:„ d:eƒZ)G d;d<„ d<eƒZ*G d=d>„ d>eƒZ+G d?d@„ d@eƒZ,G dAdB„ dBeƒZ-G dCdD„ dDeƒZ.dS )Eé    N)ÚTupleÚOptional)ÚTensoré   )Ú_LinearWithBias)Úxavier_uniform_)Ú	constant_)Úxavier_normal_)Ú	Parameter)ÚModuleé   )Ú
functionalc                       sh   e Zd ZU dZg d¢Zeed< eed< eed< deeeddœ‡ fd	d
„Ze	e	dœdd„Z
dd„ Z‡  ZS )Ú	Thresholdaº  Thresholds each element of the input Tensor.

    Threshold is defined as:

    .. math::
        y =
        \begin{cases}
        x, &\text{ if } x > \text{threshold} \\
        \text{value}, &\text{ otherwise }
        \end{cases}

    Args:
        threshold: The value to threshold at
        value: The value to replace with
        inplace: can optionally do the operation in-place. Default: ``False``

    Shape:
        - Input: :math:`(N, *)` where `*` means, any number of additional
          dimensions
        - Output: :math:`(N, *)`, same shape as the input

    Examples::

        >>> m = nn.Threshold(0.1, 20)
        >>> input = torch.randn(2)
        >>> output = m(input)
    )Ú	thresholdÚvalueÚinplacer   r   r   FN)r   r   r   Úreturnc                    s$   t t| ƒ ¡  || _|| _|| _d S ©N)Úsuperr   Ú__init__r   r   r   )Úselfr   r   r   ©Ú	__class__© ú[/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torch/nn/modules/activation.pyr   1   s    zThreshold.__init__©Úinputr   c                 C   s   t  || j| j| j¡S r   )ÚFr   r   r   ©r   r   r   r   r   Úforward8   s    zThreshold.forwardc                 C   s    | j r
dnd}d | j| j|¡S )Nú, inplace=TrueÚ zthreshold={}, value={}{})r   Úformatr   r   ©r   Zinplace_strr   r   r   Ú
extra_repr;   s    
ÿzThreshold.extra_repr)F©Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú__constants__ÚfloatÚ__annotations__Úboolr   r   r   r$   Ú__classcell__r   r   r   r   r      s   
r   c                       sV   e Zd ZU dZdgZeed< dedœ‡ fdd„Zeedœdd	„Z	e
d
œdd„Z‡  ZS )ÚReLUaÔ  Applies the rectified linear unit function element-wise:

    :math:`\text{ReLU}(x) = (x)^+ = \max(0, x)`

    Args:
        inplace: can optionally do the operation in-place. Default: ``False``

    Shape:
        - Input: :math:`(N, *)` where `*` means, any number of additional
          dimensions
        - Output: :math:`(N, *)`, same shape as the input

    .. image:: ../scripts/activation_images/ReLU.png

    Examples::

        >>> m = nn.ReLU()
        >>> input = torch.randn(2)
        >>> output = m(input)


      An implementation of CReLU - https://arxiv.org/abs/1603.05201

        >>> m = nn.ReLU()
        >>> input = torch.randn(2).unsqueeze(0)
        >>> output = torch.cat((m(input),m(-input)))
    r   F©r   c                    s   t t| ƒ ¡  || _d S r   )r   r/   r   r   ©r   r   r   r   r   r   a   s    zReLU.__init__r   c                 C   s   t j|| jd�S ©Nr0   )r   Zrelur   r   r   r   r   r   e   s    zReLU.forward©r   c                 C   s   | j r
dnd}|S ©Nzinplace=Truer!   r0   r#   r   r   r   r$   h   s    zReLU.extra_repr)F©r&   r'   r(   r)   r*   r-   r,   r   r   r   Ústrr$   r.   r   r   r   r   r/   B   s   
r/   c                       sf   e Zd ZU dZg d¢Zeed< eed< eed< deeedœ‡ fd	d
„Ze	e	dœdd„Z
dd„ Z‡  ZS )ÚRReLUa½  Applies the randomized leaky rectified liner unit function, element-wise,
    as described in the paper:

    `Empirical Evaluation of Rectified Activations in Convolutional Network`_.

    The function is defined as:

    .. math::
        \text{RReLU}(x) =
        \begin{cases}
            x & \text{if } x \geq 0 \\
            ax & \text{ otherwise }
        \end{cases}

    where :math:`a` is randomly sampled from uniform distribution
    :math:`\mathcal{U}(\text{lower}, \text{upper})`.

     See: https://arxiv.org/pdf/1505.00853.pdf

    Args:
        lower: lower bound of the uniform distribution. Default: :math:`\frac{1}{8}`
        upper: upper bound of the uniform distribution. Default: :math:`\frac{1}{3}`
        inplace: can optionally do the operation in-place. Default: ``False``

    Shape:
        - Input: :math:`(N, *)` where `*` means, any number of additional
          dimensions
        - Output: :math:`(N, *)`, same shape as the input

    Examples::

        >>> m = nn.RReLU(0.1, 0.3)
        >>> input = torch.randn(2)
        >>> output = m(input)

    .. _`Empirical Evaluation of Rectified Activations in Convolutional Network`:
        https://arxiv.org/abs/1505.00853
    )ÚlowerÚupperr   r8   r9   r   ç      À?çUUUUUUÕ?Fc                    s$   t t| ƒ ¡  || _|| _|| _d S r   )r   r7   r   r8   r9   r   )r   r8   r9   r   r   r   r   r   š   s    zRReLU.__init__r   c                 C   s   t  || j| j| j| j¡S r   )r   Zrrelur8   r9   Útrainingr   r   r   r   r   r   ¥   s    zRReLU.forwardc                 C   s    | j r
dnd}d | j| j|¡S )Nr    r!   zlower={}, upper={}{})r   r"   r8   r9   r#   r   r   r   r$   ¨   s    zRReLU.extra_repr)r:   r;   Fr%   r   r   r   r   r7   m   s   
&   üür7   c                       sz   e Zd ZU dZg d¢Zeed< eed< eed< deeeee ee d	d
œ‡ fdd„Z	e
e
dœdd„Zedœdd„Z‡  ZS )ÚHardtanhaB  Applies the HardTanh function element-wise

    HardTanh is defined as:

    .. math::
        \text{HardTanh}(x) = \begin{cases}
            1 & \text{ if } x > 1 \\
            -1 & \text{ if } x < -1 \\
            x & \text{ otherwise } \\
        \end{cases}

    The range of the linear region :math:`[-1, 1]` can be adjusted using
    :attr:`min_val` and :attr:`max_val`.

    Args:
        min_val: minimum value of the linear region range. Default: -1
        max_val: maximum value of the linear region range. Default: 1
        inplace: can optionally do the operation in-place. Default: ``False``

    Keyword arguments :attr:`min_value` and :attr:`max_value`
    have been deprecated in favor of :attr:`min_val` and :attr:`max_val`.

    Shape:
        - Input: :math:`(N, *)` where `*` means, any number of additional
          dimensions
        - Output: :math:`(N, *)`, same shape as the input

    .. image:: ../scripts/activation_images/Hardtanh.png

    Examples::

        >>> m = nn.Hardtanh(-2, 2)
        >>> input = torch.randn(2)
        >>> output = m(input)
    )Úmin_valÚmax_valr   r>   r?   r   ç      ð¿ç      ð?FN)r>   r?   r   Ú	min_valueÚ	max_valuer   c                    s`   t t| ƒ ¡  |d ur$t d¡ |}|d ur:t d¡ |}|| _|| _|| _| j| jks\J ‚d S )Nz>keyword argument min_value is deprecated and rename to min_valz>keyword argument max_value is deprecated and rename to max_val)r   r=   r   ÚwarningsÚwarnr>   r?   r   )r   r>   r?   r   rB   rC   r   r   r   r   ×   s    

zHardtanh.__init__r   c                 C   s   t  || j| j| j¡S r   )r   Zhardtanhr>   r?   r   r   r   r   r   r   ì   s    zHardtanh.forwardr3   c                 C   s    | j r
dnd}d | j| j|¡S )Nr    r!   zmin_val={}, max_val={}{})r   r"   r>   r?   r#   r   r   r   r$   ï   s    
ÿzHardtanh.extra_repr)r@   rA   FNN)r&   r'   r(   r)   r*   r+   r,   r-   r   r   r   r   r6   r$   r.   r   r   r   r   r=   ­   s(   
#     úùr=   c                       s6   e Zd ZdZd	edœ‡ fdd„Zedœdd„Z‡  ZS )
ÚReLU6a  Applies the element-wise function:

    .. math::
        \text{ReLU6}(x) = \min(\max(0,x), 6)

    Args:
        inplace: can optionally do the operation in-place. Default: ``False``

    Shape:
        - Input: :math:`(N, *)` where `*` means, any number of additional
          dimensions
        - Output: :math:`(N, *)`, same shape as the input

    .. image:: ../scripts/activation_images/ReLU6.png

    Examples::

        >>> m = nn.ReLU6()
        >>> input = torch.randn(2)
        >>> output = m(input)
    Fr0   c                    s   t t| ƒ dd|¡ d S )Nç        g      @)r   rF   r   r1   r   r   r   r     s    zReLU6.__init__r3   c                 C   s   | j r
dnd}|S r4   r0   r#   r   r   r   r$     s    zReLU6.extra_repr)F)	r&   r'   r(   r)   r-   r   r6   r$   r.   r   r   r   r   rF   ö   s   rF   c                   @   s    e Zd ZdZeedœdd„ZdS )ÚSigmoidaÃ  Applies the element-wise function:

    .. math::
        \text{Sigmoid}(x) = \sigma(x) = \frac{1}{1 + \exp(-x)}


    Shape:
        - Input: :math:`(N, *)` where `*` means, any number of additional
          dimensions
        - Output: :math:`(N, *)`, same shape as the input

    .. image:: ../scripts/activation_images/Sigmoid.png

    Examples::

        >>> m = nn.Sigmoid()
        >>> input = torch.randn(2)
        >>> output = m(input)
    r   c                 C   s
   t  |¡S r   )ÚtorchZsigmoidr   r   r   r   r   *  s    zSigmoid.forwardN©r&   r'   r(   r)   r   r   r   r   r   r   rH     s   rH   c                       sJ   e Zd ZU dZdgZeed< deddœ‡ fdd„Zeedœd	d
„Z	‡  Z
S )ÚHardsigmoidaf  Applies the element-wise function:

    .. math::
        \text{Hardsigmoid}(x) = \begin{cases}
            0 & \text{if~} x \le -3, \\
            1 & \text{if~} x \ge +3, \\
            x / 6 + 1 / 2 & \text{otherwise}
        \end{cases}

    Args:
        inplace: can optionally do the operation in-place. Default: ``False``

    Shape:
        - Input: :math:`(N, *)` where `*` means, any number of additional
          dimensions
        - Output: :math:`(N, *)`, same shape as the input

    Examples::

        >>> m = nn.Hardsigmoid()
        >>> input = torch.randn(2)
        >>> output = m(input)
    r   FN©r   r   c                    s   t t| ƒ ¡  || _d S r   )r   rK   r   r   r1   r   r   r   r   J  s    zHardsigmoid.__init__r   c                 C   s   t  || j¡S r   )r   Zhardsigmoidr   r   r   r   r   r   N  s    zHardsigmoid.forward)F©r&   r'   r(   r)   r*   r-   r,   r   r   r   r.   r   r   r   r   rK   .  s
   
rK   c                   @   s    e Zd ZdZeedœdd„ZdS )ÚTanhaÐ  Applies the element-wise function:

    .. math::
        \text{Tanh}(x) = \tanh(x) = \frac{\exp(x) - \exp(-x)} {\exp(x) + \exp(-x)}

    Shape:
        - Input: :math:`(N, *)` where `*` means, any number of additional
          dimensions
        - Output: :math:`(N, *)`, same shape as the input

    .. image:: ../scripts/activation_images/Tanh.png

    Examples::

        >>> m = nn.Tanh()
        >>> input = torch.randn(2)
        >>> output = m(input)
    r   c                 C   s
   t  |¡S r   )rI   Útanhr   r   r   r   r   f  s    zTanh.forwardNrJ   r   r   r   r   rN   R  s   rN   c                       sV   e Zd ZU dZdgZeed< dedœ‡ fdd„Zeedœdd	„Z	e
d
œdd„Z‡  ZS )ÚSiLUaŒ  Applies the silu function, element-wise.

    .. math::
        \text{silu}(x) = x * \sigma(x), \text{where } \sigma(x) \text{ is the logistic sigmoid.}

    .. note::
        See `Gaussian Error Linear Units (GELUs) <https://arxiv.org/abs/1606.08415>`_ 
        where the SiLU (Sigmoid Linear Unit) was originally coined, and see 
        `Sigmoid-Weighted Linear Units for Neural Network Function Approximation 
        in Reinforcement Learning <https://arxiv.org/abs/1702.03118>`_ and `Swish: 
        a Self-Gated Activation Function <https://arxiv.org/abs/1710.05941v1>`_ 
        where the SiLU was experimented with later.

    Shape:
        - Input: :math:`(N, *)` where `*` means, any number of additional
          dimensions
        - Output: :math:`(N, *)`, same shape as the input

    Examples::

        >>> m = nn.SiLU()
        >>> input = torch.randn(2)
        >>> output = m(input)
    r   Fr0   c                    s   t t| ƒ ¡  || _d S r   )r   rP   r   r   r1   r   r   r   r   …  s    zSiLU.__init__r   c                 C   s   t j|| jd�S r2   )r   Zsilur   r   r   r   r   r   ‰  s    zSiLU.forwardr3   c                 C   s   | j r
dnd}|S r4   r0   r#   r   r   r   r$   Œ  s    zSiLU.extra_repr)Fr5   r   r   r   r   rP   i  s   
rP   c                       sJ   e Zd ZU dZdgZeed< deddœ‡ fdd„Zeedœd	d
„Z	‡  Z
S )Ú	Hardswishaÿ  Applies the hardswish function, element-wise, as described in the paper:

    `Searching for MobileNetV3`_.

    .. math::
        \text{Hardswish}(x) = \begin{cases}
            0 & \text{if~} x \le -3, \\
            x & \text{if~} x \ge +3, \\
            x \cdot (x + 3) /6 & \text{otherwise}
        \end{cases}

    Args:
        inplace: can optionally do the operation in-place. Default: ``False``

    Shape:
        - Input: :math:`(N, *)` where `*` means, any number of additional
          dimensions
        - Output: :math:`(N, *)`, same shape as the input

    Examples::

        >>> m = nn.Hardswish()
        >>> input = torch.randn(2)
        >>> output = m(input)

    .. _`Searching for MobileNetV3`:
        https://arxiv.org/abs/1905.02244
    r   FNrL   c                    s   t t| ƒ ¡  || _d S r   )r   rQ   r   r   r1   r   r   r   r   ±  s    zHardswish.__init__r   c                 C   s   t  || j¡S r   )r   Z	hardswishr   r   r   r   r   r   µ  s    zHardswish.forward)FrM   r   r   r   r   rQ   �  s
   
rQ   c                       sd   e Zd ZU dZddgZeed< eed< deeddœ‡ fdd	„Ze	e	d
œdd„Z
edœdd„Z‡  ZS )ÚELUa´  Applies the element-wise function:

    .. math::
        \text{ELU}(x) = \begin{cases}
        x, & \text{ if } x > 0\\
        \alpha * (\exp(x) - 1), & \text{ if } x \leq 0
        \end{cases}

    Args:
        alpha: the :math:`\alpha` value for the ELU formulation. Default: 1.0
        inplace: can optionally do the operation in-place. Default: ``False``

    Shape:
        - Input: :math:`(N, *)` where `*` means, any number of additional
          dimensions
        - Output: :math:`(N, *)`, same shape as the input

    .. image:: ../scripts/activation_images/ELU.png

    Examples::

        >>> m = nn.ELU()
        >>> input = torch.randn(2)
        >>> output = m(input)
    Úalphar   rA   FN©rS   r   r   c                    s   t t| ƒ ¡  || _|| _d S r   )r   rR   r   rS   r   ©r   rS   r   r   r   r   r   ×  s    zELU.__init__r   c                 C   s   t  || j| j¡S r   )r   ZelurS   r   r   r   r   r   r   Ü  s    zELU.forwardr3   c                 C   s   | j r
dnd}d | j|¡S ©Nr    r!   z
alpha={}{}©r   r"   rS   r#   r   r   r   r$   ß  s    zELU.extra_repr)rA   F©r&   r'   r(   r)   r*   r+   r,   r-   r   r   r   r6   r$   r.   r   r   r   r   rR   ¹  s   
rR   c                       sd   e Zd ZU dZddgZeed< eed< deeddœ‡ fdd	„Ze	e	d
œdd„Z
edœdd„Z‡  ZS )ÚCELUaA  Applies the element-wise function:

    .. math::
        \text{CELU}(x) = \max(0,x) + \min(0, \alpha * (\exp(x/\alpha) - 1))

    More details can be found in the paper `Continuously Differentiable Exponential Linear Units`_ .

    Args:
        alpha: the :math:`\alpha` value for the CELU formulation. Default: 1.0
        inplace: can optionally do the operation in-place. Default: ``False``

    Shape:
        - Input: :math:`(N, *)` where `*` means, any number of additional
          dimensions
        - Output: :math:`(N, *)`, same shape as the input

    .. image:: ../scripts/activation_images/CELU.png

    Examples::

        >>> m = nn.CELU()
        >>> input = torch.randn(2)
        >>> output = m(input)

    .. _`Continuously Differentiable Exponential Linear Units`:
        https://arxiv.org/abs/1704.07483
    rS   r   rA   FNrT   c                    s   t t| ƒ ¡  || _|| _d S r   )r   rY   r   rS   r   rU   r   r   r   r     s    zCELU.__init__r   c                 C   s   t  || j| j¡S r   )r   ZcelurS   r   r   r   r   r   r   	  s    zCELU.forwardr3   c                 C   s   | j r
dnd}d | j|¡S rV   rW   r#   r   r   r   r$     s    zCELU.extra_repr)rA   FrX   r   r   r   r   rY   ä  s   
rY   c                       sX   e Zd ZU dZdgZeed< deddœ‡ fdd„Zeedœd	d
„Z	e
dœdd„Z‡  ZS )ÚSELUaQ  Applied element-wise, as:

    .. math::
        \text{SELU}(x) = \text{scale} * (\max(0,x) + \min(0, \alpha * (\exp(x) - 1)))

    with :math:`\alpha = 1.6732632423543772848170429916717` and
    :math:`\text{scale} = 1.0507009873554804934193349852946`.

    More details can be found in the paper `Self-Normalizing Neural Networks`_ .

    Args:
        inplace (bool, optional): can optionally do the operation in-place. Default: ``False``

    Shape:
        - Input: :math:`(N, *)` where `*` means, any number of additional
          dimensions
        - Output: :math:`(N, *)`, same shape as the input

    .. image:: ../scripts/activation_images/SELU.png

    Examples::

        >>> m = nn.SELU()
        >>> input = torch.randn(2)
        >>> output = m(input)

    .. _Self-Normalizing Neural Networks: https://arxiv.org/abs/1706.02515
    r   FNrL   c                    s   t t| ƒ ¡  || _d S r   )r   rZ   r   r   r1   r   r   r   r   1  s    zSELU.__init__r   c                 C   s   t  || j¡S r   )r   Zselur   r   r   r   r   r   5  s    zSELU.forwardr3   c                 C   s   | j r
dnd}|S r4   r0   r#   r   r   r   r$   8  s    zSELU.extra_repr)Fr5   r   r   r   r   rZ     s   
rZ   c                       sX   e Zd ZU dZdgZeed< deddœ‡ fdd„Zeedœd	d
„Z	e
dœdd„Z‡  ZS )ÚGLUa3  Applies the gated linear unit function
    :math:`{GLU}(a, b)= a \otimes \sigma(b)` where :math:`a` is the first half
    of the input matrices and :math:`b` is the second half.

    Args:
        dim (int): the dimension on which to split the input. Default: -1

    Shape:
        - Input: :math:`(\ast_1, N, \ast_2)` where `*` means, any number of additional
          dimensions
        - Output: :math:`(\ast_1, M, \ast_2)` where :math:`M=N/2`

    Examples::

        >>> m = nn.GLU()
        >>> input = torch.randn(4, 2)
        >>> output = m(input)
    ÚdiméÿÿÿÿN©r\   r   c                    s   t t| ƒ ¡  || _d S r   )r   r[   r   r\   ©r   r\   r   r   r   r   S  s    zGLU.__init__r   c                 C   s   t  || j¡S r   )r   Zglur\   r   r   r   r   r   W  s    zGLU.forwardr3   c                 C   s   d  | j¡S )Nzdim={}©r"   r\   ©r   r   r   r   r$   Z  s    zGLU.extra_repr)r]   ©r&   r'   r(   r)   r*   Úintr,   r   r   r   r6   r$   r.   r   r   r   r   r[   =  s   
r[   c                   @   s    e Zd ZdZeedœdd„ZdS )ÚGELUa  Applies the Gaussian Error Linear Units function:

    .. math:: \text{GELU}(x) = x * \Phi(x)

    where :math:`\Phi(x)` is the Cumulative Distribution Function for Gaussian Distribution.

    Shape:
        - Input: :math:`(N, *)` where `*` means, any number of additional
          dimensions
        - Output: :math:`(N, *)`, same shape as the input

    .. image:: ../scripts/activation_images/GELU.png

    Examples::

        >>> m = nn.GELU()
        >>> input = torch.randn(2)
        >>> output = m(input)
    r   c                 C   s
   t  |¡S r   )r   Zgelur   r   r   r   r   r  s    zGELU.forwardNrJ   r   r   r   r   rd   ^  s   rd   c                       sX   e Zd ZU dZdgZeed< deddœ‡ fdd„Zeedœd	d
„Z	e
dœdd„Z‡  ZS )Ú
Hardshrinka³  Applies the hard shrinkage function element-wise:

    .. math::
        \text{HardShrink}(x) =
        \begin{cases}
        x, & \text{ if } x > \lambda \\
        x, & \text{ if } x < -\lambda \\
        0, & \text{ otherwise }
        \end{cases}

    Args:
        lambd: the :math:`\lambda` value for the Hardshrink formulation. Default: 0.5

    Shape:
        - Input: :math:`(N, *)` where `*` means, any number of additional
          dimensions
        - Output: :math:`(N, *)`, same shape as the input

    .. image:: ../scripts/activation_images/Hardshrink.png

    Examples::

        >>> m = nn.Hardshrink()
        >>> input = torch.randn(2)
        >>> output = m(input)
    Úlambdç      à?N©rf   r   c                    s   t t| ƒ ¡  || _d S r   )r   re   r   rf   ©r   rf   r   r   r   r   ”  s    zHardshrink.__init__r   c                 C   s   t  || j¡S r   )r   Z
hardshrinkrf   r   r   r   r   r   ˜  s    zHardshrink.forwardr3   c                 C   s   d  | j¡S )Nz{})r"   rf   ra   r   r   r   r$   ›  s    zHardshrink.extra_repr)rg   ©r&   r'   r(   r)   r*   r+   r,   r   r   r   r6   r$   r.   r   r   r   r   re   v  s   
re   c                       sd   e Zd ZU dZddgZeed< eed< deeddœ‡ fdd	„Ze	e	d
œdd„Z
edœdd„Z‡  ZS )Ú	LeakyReLUaE  Applies the element-wise function:

    .. math::
        \text{LeakyReLU}(x) = \max(0, x) + \text{negative\_slope} * \min(0, x)


    or

    .. math::
        \text{LeakyRELU}(x) =
        \begin{cases}
        x, & \text{ if } x \geq 0 \\
        \text{negative\_slope} \times x, & \text{ otherwise }
        \end{cases}

    Args:
        negative_slope: Controls the angle of the negative slope. Default: 1e-2
        inplace: can optionally do the operation in-place. Default: ``False``

    Shape:
        - Input: :math:`(N, *)` where `*` means, any number of additional
          dimensions
        - Output: :math:`(N, *)`, same shape as the input

    .. image:: ../scripts/activation_images/LeakyReLU.png

    Examples::

        >>> m = nn.LeakyReLU(0.1)
        >>> input = torch.randn(2)
        >>> output = m(input)
    r   Únegative_slopeç{®Gáz„?FN)rl   r   r   c                    s   t t| ƒ ¡  || _|| _d S r   )r   rk   r   rl   r   )r   rl   r   r   r   r   r   Ä  s    zLeakyReLU.__init__r   c                 C   s   t  || j| j¡S r   )r   Z
leaky_relurl   r   r   r   r   r   r   É  s    zLeakyReLU.forwardr3   c                 C   s   | j r
dnd}d | j|¡S )Nr    r!   znegative_slope={}{})r   r"   rl   r#   r   r   r   r$   Ì  s    zLeakyReLU.extra_repr)rm   F)r&   r'   r(   r)   r*   r-   r,   r+   r   r   r   r6   r$   r.   r   r   r   r   rk   Ÿ  s   
 rk   c                   @   s    e Zd ZdZeedœdd„ZdS )Ú
LogSigmoidaÓ  Applies the element-wise function:

    .. math::
        \text{LogSigmoid}(x) = \log\left(\frac{ 1 }{ 1 + \exp(-x)}\right)

    Shape:
        - Input: :math:`(N, *)` where `*` means, any number of additional
          dimensions
        - Output: :math:`(N, *)`, same shape as the input

    .. image:: ../scripts/activation_images/LogSigmoid.png

    Examples::

        >>> m = nn.LogSigmoid()
        >>> input = torch.randn(2)
        >>> output = m(input)
    r   c                 C   s
   t  |¡S r   )r   Z
logsigmoidr   r   r   r   r   å  s    zLogSigmoid.forwardNrJ   r   r   r   r   rn   Ñ  s   rn   c                       sd   e Zd ZU dZddgZeed< eed< deeddœ‡ fdd	„Zeed
œdd„Z	e
dœdd„Z‡  ZS )ÚSoftplusaƒ  Applies the element-wise function:

    .. math::
        \text{Softplus}(x) = \frac{1}{\beta} * \log(1 + \exp(\beta * x))

    SoftPlus is a smooth approximation to the ReLU function and can be used
    to constrain the output of a machine to always be positive.

    For numerical stability the implementation reverts to the linear function
    when :math:`input \times \beta > threshold`.

    Args:
        beta: the :math:`\beta` value for the Softplus formulation. Default: 1
        threshold: values above this revert to a linear function. Default: 20

    Shape:
        - Input: :math:`(N, *)` where `*` means, any number of additional
          dimensions
        - Output: :math:`(N, *)`, same shape as the input

    .. image:: ../scripts/activation_images/Softplus.png

    Examples::

        >>> m = nn.Softplus()
        >>> input = torch.randn(2)
        >>> output = m(input)
    Úbetar   r   é   N)rp   r   r   c                    s   t t| ƒ ¡  || _|| _d S r   )r   ro   r   rp   r   )r   rp   r   r   r   r   r   
  s    zSoftplus.__init__r   c                 C   s   t  || j| j¡S r   )r   Zsoftplusrp   r   r   r   r   r   r     s    zSoftplus.forwardr3   c                 C   s   d  | j| j¡S )Nzbeta={}, threshold={})r"   rp   r   ra   r   r   r   r$     s    zSoftplus.extra_repr)r   rq   rb   r   r   r   r   ro   é  s   
ro   c                       sX   e Zd ZU dZdgZeed< deddœ‡ fdd„Zeedœd	d
„Z	e
dœdd„Z‡  ZS )Ú
Softshrinkaå  Applies the soft shrinkage function elementwise:

    .. math::
        \text{SoftShrinkage}(x) =
        \begin{cases}
        x - \lambda, & \text{ if } x > \lambda \\
        x + \lambda, & \text{ if } x < -\lambda \\
        0, & \text{ otherwise }
        \end{cases}

    Args:
        lambd: the :math:`\lambda` (must be no less than zero) value for the Softshrink formulation. Default: 0.5

    Shape:
        - Input: :math:`(N, *)` where `*` means, any number of additional
          dimensions
        - Output: :math:`(N, *)`, same shape as the input

    .. image:: ../scripts/activation_images/Softshrink.png

    Examples::

        >>> m = nn.Softshrink()
        >>> input = torch.randn(2)
        >>> output = m(input)
    rf   rg   Nrh   c                    s   t t| ƒ ¡  || _d S r   )r   rr   r   rf   ri   r   r   r   r   4  s    zSoftshrink.__init__r   c                 C   s   t  || j¡S r   )r   Z
softshrinkrf   r   r   r   r   r   8  s    zSoftshrink.forwardr3   c                 C   s
   t | jƒS r   )r6   rf   ra   r   r   r   r$   ;  s    zSoftshrink.extra_repr)rg   rj   r   r   r   r   rr     s   
rr   c                       s^   e Zd ZU dZeej ed< eej ed< d‡ fdd	„	Zd
d„ Z	‡ fdd„Z
ddd„Z‡  ZS )ÚMultiheadAttentiona�  Allows the model to jointly attend to information
    from different representation subspaces.
    See reference: Attention Is All You Need

    .. math::
        \text{MultiHead}(Q, K, V) = \text{Concat}(head_1,\dots,head_h)W^O
        \text{where} head_i = \text{Attention}(QW_i^Q, KW_i^K, VW_i^V)

    Args:
        embed_dim: total dimension of the model.
        num_heads: parallel attention heads.
        dropout: a Dropout layer on attn_output_weights. Default: 0.0.
        bias: add bias as module parameter. Default: True.
        add_bias_kv: add bias to the key and value sequences at dim=0.
        add_zero_attn: add a new batch of zeros to the key and
                       value sequences at dim=1.
        kdim: total number of features in key. Default: None.
        vdim: total number of features in value. Default: None.

        Note: if kdim and vdim are None, they will be set to embed_dim such that
        query, key, and value have the same number of features.

    Examples::

        >>> multihead_attn = nn.MultiheadAttention(embed_dim, num_heads)
        >>> attn_output, attn_output_weights = multihead_attn(query, key, value)
    Úbias_kÚbias_vrG   TFNc	           	         sŠ  t t| ƒ ¡  || _|d ur |n|| _|d ur2|n|| _| j|koJ| j|k| _|| _|| _|| | _	| j	| | jks|J dƒ‚| jdu rÎt
t ||¡ƒ| _t
t || j¡ƒ| _t
t || j¡ƒ| _|  dd ¡ n:t
t d| |¡ƒ| _|  dd ¡ |  dd ¡ |  dd ¡ |�r$t
t d| ¡ƒ| _n|  dd ¡ t||ƒ| _|�rlt
t d	d	|¡ƒ| _t
t d	d	|¡ƒ| _nd  | _| _|| _|  ¡  d S )
Nz(embed_dim must be divisible by num_headsFÚin_proj_weighté   Úq_proj_weightÚk_proj_weightÚv_proj_weightÚin_proj_biasr   )r   rs   r   Ú	embed_dimÚkdimÚvdimÚ_qkv_same_embed_dimÚ	num_headsÚdropoutZhead_dimr
   rI   r   rx   ry   rz   Zregister_parameterÚemptyrv   r{   r   Úout_projrt   ru   Úadd_zero_attnÚ_reset_parameters)	r   r|   r€   r�   ÚbiasZadd_bias_kvr„   r}   r~   r   r   r   r   ^  s8    

zMultiheadAttention.__init__c                 C   s€   | j rt| jƒ nt| jƒ t| jƒ t| jƒ | jd urTt| jdƒ t| jj	dƒ | j
d urht| j
ƒ | jd ur|t| jƒ d S )NrG   )r   r   rv   rx   ry   rz   r{   r   rƒ   r†   rt   r	   ru   ra   r   r   r   r…   …  s    






z$MultiheadAttention._reset_parametersc                    s$   d|vrd|d< t t| ƒ |¡ d S )Nr   T)r   rs   Ú__setstate__©r   Ústater   r   r   r‡   •  s    zMultiheadAttention.__setstate__c                 C   s¤   | j sZtj|||| j| j| j| j| j| j| j	| j
| jj| jj| j|||d| j| j| jd�S tj|||| j| j| j| j| j| j| j	| j
| jj| jj| j|||d�S dS )as
  
    Args:
        query, key, value: map a query and a set of key-value pairs to an output.
            See "Attention Is All You Need" for more details.
        key_padding_mask: if provided, specified padding elements in the key will
            be ignored by the attention. When given a binary mask and a value is True,
            the corresponding value on the attention layer will be ignored. When given
            a byte mask and a value is non-zero, the corresponding value on the attention
            layer will be ignored
        need_weights: output attn_output_weights.
        attn_mask: 2D or 3D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all
            the batches while a 3D mask allows to specify a different mask for the entries of each batch.

    Shape:
        - Inputs:
        - query: :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is
          the embedding dimension.
        - key: :math:`(S, N, E)`, where S is the source sequence length, N is the batch size, E is
          the embedding dimension.
        - value: :math:`(S, N, E)` where S is the source sequence length, N is the batch size, E is
          the embedding dimension.
        - key_padding_mask: :math:`(N, S)` where N is the batch size, S is the source sequence length.
          If a ByteTensor is provided, the non-zero positions will be ignored while the position
          with the zero positions will be unchanged. If a BoolTensor is provided, the positions with the
          value of ``True`` will be ignored while the position with the value of ``False`` will be unchanged.
        - attn_mask: 2D mask :math:`(L, S)` where L is the target sequence length, S is the source sequence length.
          3D mask :math:`(N*num_heads, L, S)` where N is the batch size, L is the target sequence length,
          S is the source sequence length. attn_mask ensure that position i is allowed to attend the unmasked
          positions. If a ByteTensor is provided, the non-zero positions are not allowed to attend
          while the zero positions will be unchanged. If a BoolTensor is provided, positions with ``True``
          is not allowed to attend while ``False`` values will be unchanged. If a FloatTensor
          is provided, it will be added to the attention weight.

        - Outputs:
        - attn_output: :math:`(L, N, E)` where L is the target sequence length, N is the batch size,
          E is the embedding dimension.
        - attn_output_weights: :math:`(N, L, S)` where N is the batch size,
          L is the target sequence length, S is the source sequence length.
        T)r<   Úkey_padding_maskÚneed_weightsÚ	attn_maskZuse_separate_proj_weightrx   ry   rz   )r<   rŠ   r‹   rŒ   N)r   r   Zmulti_head_attention_forwardr|   r€   rv   r{   rt   ru   r„   r�   rƒ   Úweightr†   r<   rx   ry   rz   )r   ÚqueryÚkeyr   rŠ   r‹   rŒ   r   r   r   r   œ  s*    *÷ùzMultiheadAttention.forward)rG   TFFNN)NTN)r&   r'   r(   r)   r   rI   r   r,   r   r…   r‡   r   r.   r   r   r   r   rs   ?  s   
'  ÿrs   c                       sZ   e Zd ZU dZdgZeed< deeddœ‡ fdd„Ze	e	d	œd
d„Z
edœdd„Z‡  ZS )ÚPReLUaÒ  Applies the element-wise function:

    .. math::
        \text{PReLU}(x) = \max(0,x) + a * \min(0,x)

    or

    .. math::
        \text{PReLU}(x) =
        \begin{cases}
        x, & \text{ if } x \geq 0 \\
        ax, & \text{ otherwise }
        \end{cases}

    Here :math:`a` is a learnable parameter. When called without arguments, `nn.PReLU()` uses a single
    parameter :math:`a` across all input channels. If called with `nn.PReLU(nChannels)`,
    a separate :math:`a` is used for each input channel.


    .. note::
        weight decay should not be used when learning :math:`a` for good performance.

    .. note::
        Channel dim is the 2nd dim of input. When input has dims < 2, then there is
        no channel dim and the number of channels = 1.

    Args:
        num_parameters (int): number of :math:`a` to learn.
            Although it takes an int as input, there is only two values are legitimate:
            1, or the number of channels at input. Default: 1
        init (float): the initial value of :math:`a`. Default: 0.25

    Shape:
        - Input: :math:`(N, *)` where `*` means, any number of additional
          dimensions
        - Output: :math:`(N, *)`, same shape as the input

    Attributes:
        weight (Tensor): the learnable weights of shape (:attr:`num_parameters`).

    .. image:: ../scripts/activation_images/PReLU.png

    Examples::

        >>> m = nn.PReLU()
        >>> input = torch.randn(2)
        >>> output = m(input)
    Únum_parametersr   ç      Ð?N)r‘   Úinitr   c                    s.   || _ tt| ƒ ¡  tt |¡ |¡ƒ| _d S r   )	r‘   r   r�   r   r
   rI   r   Zfill_r�   )r   r‘   r“   r   r   r   r     s    zPReLU.__init__r   c                 C   s   t  || j¡S r   )r   Zprelur�   r   r   r   r   r     s    zPReLU.forwardr3   c                 C   s   d  | j¡S )Nznum_parameters={})r"   r‘   ra   r   r   r   r$     s    zPReLU.extra_repr)r   r’   )r&   r'   r(   r)   r*   rc   r,   r+   r   r   r   r6   r$   r.   r   r   r   r   r�   Ü  s   
0r�   c                   @   s    e Zd ZdZeedœdd„ZdS )ÚSoftsignaµ  Applies the element-wise function:

    .. math::
        \text{SoftSign}(x) = \frac{x}{ 1 + |x|}

    Shape:
        - Input: :math:`(N, *)` where `*` means, any number of additional
          dimensions
        - Output: :math:`(N, *)`, same shape as the input

    .. image:: ../scripts/activation_images/Softsign.png

    Examples::

        >>> m = nn.Softsign()
        >>> input = torch.randn(2)
        >>> output = m(input)
    r   c                 C   s
   t  |¡S r   )r   Zsoftsignr   r   r   r   r   0  s    zSoftsign.forwardNrJ   r   r   r   r   r”     s   r”   c                   @   s    e Zd ZdZeedœdd„ZdS )Ú
Tanhshrinkaµ  Applies the element-wise function:

    .. math::
        \text{Tanhshrink}(x) = x - \tanh(x)

    Shape:
        - Input: :math:`(N, *)` where `*` means, any number of additional
          dimensions
        - Output: :math:`(N, *)`, same shape as the input

    .. image:: ../scripts/activation_images/Tanhshrink.png

    Examples::

        >>> m = nn.Tanhshrink()
        >>> input = torch.randn(2)
        >>> output = m(input)
    r   c                 C   s
   t  |¡S r   )r   Z
tanhshrinkr   r   r   r   r   H  s    zTanhshrink.forwardNrJ   r   r   r   r   r•   4  s   r•   c                       sb   e Zd ZU dZdgZee ed< dee ddœ‡ fdd„Zdd„ Z	e
e
d	œd
d„Zdd„ Z‡  ZS )ÚSoftmina9  Applies the Softmin function to an n-dimensional input Tensor
    rescaling them so that the elements of the n-dimensional output Tensor
    lie in the range `[0, 1]` and sum to 1.

    Softmin is defined as:

    .. math::
        \text{Softmin}(x_{i}) = \frac{\exp(-x_i)}{\sum_j \exp(-x_j)}

    Shape:
        - Input: :math:`(*)` where `*` means, any number of additional
          dimensions
        - Output: :math:`(*)`, same shape as the input

    Arguments:
        dim (int): A dimension along which Softmin will be computed (so every slice
            along dim will sum to 1).

    Returns:
        a Tensor of the same dimension and shape as the input, with
        values in the range [0, 1]

    Examples::

        >>> m = nn.Softmin()
        >>> input = torch.randn(2, 3)
        >>> output = m(input)
    r\   Nr^   c                    s   t t| ƒ ¡  || _d S r   )r   r–   r   r\   r_   r   r   r   r   l  s    zSoftmin.__init__c                 C   s    | j  |¡ t| dƒsd | _d S ©Nr\   ©Ú__dict__ÚupdateÚhasattrr\   rˆ   r   r   r   r‡   p  s    
zSoftmin.__setstate__r   c                 C   s   t j|| jdd�S ©Né   ©Z_stacklevel)r   Zsoftminr\   r   r   r   r   r   u  s    zSoftmin.forwardc                 C   s   dj | jd�S ©Nz	dim={dim})r\   r`   ra   r   r   r   r$   x  s    zSoftmin.extra_repr)N©r&   r'   r(   r)   r*   r   rc   r,   r   r‡   r   r   r$   r.   r   r   r   r   r–   L  s   
r–   c                       sh   e Zd ZU dZdgZee ed< dee ddœ‡ fdd„Zdd„ Z	e
e
d	œd
d„Zedœdd„Z‡  ZS )ÚSoftmaxa‡  Applies the Softmax function to an n-dimensional input Tensor
    rescaling them so that the elements of the n-dimensional output Tensor
    lie in the range [0,1] and sum to 1.

    Softmax is defined as:

    .. math::
        \text{Softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}

    When the input Tensor is a sparse tensor then the unspecifed
    values are treated as ``-inf``.

    Shape:
        - Input: :math:`(*)` where `*` means, any number of additional
          dimensions
        - Output: :math:`(*)`, same shape as the input

    Returns:
        a Tensor of the same dimension and shape as the input with
        values in the range [0, 1]

    Arguments:
        dim (int): A dimension along which Softmax will be computed (so every slice
            along dim will sum to 1).

    .. note::
        This module doesn't work directly with NLLLoss,
        which expects the Log to be computed between the Softmax and itself.
        Use `LogSoftmax` instead (it's faster and has better numerical properties).

    Examples::

        >>> m = nn.Softmax(dim=1)
        >>> input = torch.randn(2, 3)
        >>> output = m(input)

    r\   Nr^   c                    s   t t| ƒ ¡  || _d S r   )r   r¡   r   r\   r_   r   r   r   r   ¤  s    zSoftmax.__init__c                 C   s    | j  |¡ t| dƒsd | _d S r—   r˜   rˆ   r   r   r   r‡   ¨  s    
zSoftmax.__setstate__r   c                 C   s   t j|| jdd�S rœ   )r   Úsoftmaxr\   r   r   r   r   r   ­  s    zSoftmax.forwardr3   c                 C   s   dj | jd�S rŸ   r`   ra   r   r   r   r$   °  s    zSoftmax.extra_repr)N)r&   r'   r(   r)   r*   r   rc   r,   r   r‡   r   r   r6   r$   r.   r   r   r   r   r¡   {  s   
%r¡   c                   @   s    e Zd ZdZeedœdd„ZdS )Ú	Softmax2daQ  Applies SoftMax over features to each spatial location.

    When given an image of ``Channels x Height x Width``, it will
    apply `Softmax` to each location :math:`(Channels, h_i, w_j)`

    Shape:
        - Input: :math:`(N, C, H, W)`
        - Output: :math:`(N, C, H, W)` (same shape as input)

    Returns:
        a Tensor of the same dimension and shape as the input with
        values in the range [0, 1]

    Examples::

        >>> m = nn.Softmax2d()
        >>> # you softmax over the 2nd dimension
        >>> input = torch.randn(2, 3, 12, 13)
        >>> output = m(input)
    r   c                 C   s$   |  ¡ dksJ dƒ‚tj|ddd�S )Né   z'Softmax2d requires a 4D tensor as inputr   r�   rž   )r\   r   r¢   r   r   r   r   r   Ê  s    zSoftmax2d.forwardNrJ   r   r   r   r   r£   ´  s   r£   c                       sb   e Zd ZU dZdgZee ed< dee ddœ‡ fdd„Zdd„ Z	e
e
d	œd
d„Zdd„ Z‡  ZS )Ú
LogSoftmaxaÜ  Applies the :math:`\log(\text{Softmax}(x))` function to an n-dimensional
    input Tensor. The LogSoftmax formulation can be simplified as:

    .. math::
        \text{LogSoftmax}(x_{i}) = \log\left(\frac{\exp(x_i) }{ \sum_j \exp(x_j)} \right)

    Shape:
        - Input: :math:`(*)` where `*` means, any number of additional
          dimensions
        - Output: :math:`(*)`, same shape as the input

    Arguments:
        dim (int): A dimension along which LogSoftmax will be computed.

    Returns:
        a Tensor of the same dimension and shape as the input with
        values in the range [-inf, 0)

    Examples::

        >>> m = nn.LogSoftmax()
        >>> input = torch.randn(2, 3)
        >>> output = m(input)
    r\   Nr^   c                    s   t t| ƒ ¡  || _d S r   )r   r¥   r   r\   r_   r   r   r   r   ë  s    zLogSoftmax.__init__c                 C   s    | j  |¡ t| dƒsd | _d S r—   r˜   rˆ   r   r   r   r‡   ï  s    
zLogSoftmax.__setstate__r   c                 C   s   t j|| jdd�S rœ   )r   Zlog_softmaxr\   r   r   r   r   r   ô  s    zLogSoftmax.forwardc                 C   s   dj | jd�S rŸ   r`   ra   r   r   r   r$   ÷  s    zLogSoftmax.extra_repr)Nr    r   r   r   r   r¥   Ï  s   
r¥   )/rD   Útypingr   r   rI   r   Zlinearr   Ztorch.nn.initr   r   r	   Ztorch.nn.parameterr
   Úmoduler   r!   r   r   r   r/   r7   r=   rF   rH   rK   rN   rP   rQ   rR   rY   rZ   r[   rd   re   rk   rn   ro   rr   rs   r�   r”   r•   r–   r¡   r£   r¥   r   r   r   r   Ú<module>   sN   3+@I$')+-,!)2-) @/9