o
    hG                     @   s  d dl Z d dlmZ d dlZd dlm  mZ d dlmZ d dl	m
Z
mZmZ d dlmZ ddlmZ ddlmZ g d	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,d- d-eZ%G d.d/ d/eZ&G d0d1 d1eZ'G d2d3 d3eZ(d4eej d5e)fd6d7Z*d4eej d5e)fd8d9Z+d:d; Z,G d<d= d=eZ-G d>d? d?eZ.G d@dA dAeZ/G dBdC dCeZ0G dDdE dEeZ1G dFdG dGeZ2G dHdI dIeZ3G dJdK dKeZ4dS )L    N)Optional)Tensor)	constant_xavier_normal_xavier_uniform_)	Parameter   )NonDynamicallyQuantizableLinear)Module)	ThresholdReLURReLUHardtanhReLU6SigmoidHardsigmoidTanhSiLUMish	HardswishELUCELUSELUGLUGELU
Hardshrink	LeakyReLU
LogSigmoidSoftplus
SoftshrinkMultiheadAttentionPReLUSoftsign
TanhshrinkSoftminSoftmax	Softmax2d
LogSoftmaxc                	       sp   e Zd ZU dZg dZeed< eed< eed< ddedededdf fd	d
Zde	de	fddZ
dd Z  ZS )r   a  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:`(*)`, where :math:`*` means any number of dimensions.
        - Output: :math:`(*)`, same shape as the input.

    Examples::

        >>> m = nn.Threshold(0.1, 20)
        >>> input = torch.randn(2)
        >>> output = m(input)
    )	thresholdvalueinplacer(   r)   r*   FreturnNc                        t    || _|| _|| _d S N)super__init__r(   r)   r*   )selfr(   r)   r*   	__class__ o/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/torch/nn/modules/activation.pyr/   R   s   

zThreshold.__init__inputc                 C   s   t || j| j| jS r-   )Fr(   r)   r*   r0   r5   r3   r3   r4   forwardY      zThreshold.forwardc                 C   &   | j rdnd}d| j d| j | S )N, inplace=True z
threshold=z, value=)r*   r(   r)   r0   inplace_strr3   r3   r4   
extra_repr\      zThreshold.extra_reprF__name__
__module____qualname____doc____constants__float__annotations__boolr/   r   r8   r?   __classcell__r3   r3   r1   r4   r   0   s   
  r   c                       X   e Zd ZU dZdgZeed< ddef fddZdedefdd	Z	de
fd
dZ  ZS )r   a  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:`(*)`, where :math:`*` means any number of dimensions.
        - Output: :math:`(*)`, 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*   Fc                       t    || _d S r-   r.   r/   r*   r0   r*   r1   r3   r4   r/         

zReLU.__init__r5   r+   c                 C      t j|| jdS Nr*   )r6   relur*   r7   r3   r3   r4   r8         zReLU.forwardc                 C      | j rd}|S d}|S Nzinplace=Truer<   rS   r=   r3   r3   r4   r?         
zReLU.extra_reprrA   rC   rD   rE   rF   rG   rJ   rI   r/   r   r8   strr?   rK   r3   r3   r1   r4   r   a   s   
 r   c                       sn   e Zd ZU dZg dZeed< eed< eed< 	ddededef fd	d
Zde	de	fddZ
dd Z  ZS )r   a  Applies the randomized leaky rectified linear unit function, element-wise.

    Method described in the paper:
    `Empirical Evaluation of Rectified Activations in Convolutional Network <https://arxiv.org/abs/1505.00853>`_.

    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})` during training while during
    evaluation :math:`a` is fixed with :math:`a = \frac{\text{lower} + \text{upper}}{2}`.

    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:`(*)`, where :math:`*` means any number of dimensions.
        - Output: :math:`(*)`, same shape as the input.

    .. image:: ../scripts/activation_images/RReLU.png

    Examples::

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

    )lowerupperr*   r[   r\   r*         ?UUUUUU?Fc                    r,   r-   )r.   r/   r[   r\   r*   )r0   r[   r\   r*   r1   r3   r4   r/      s   

zRReLU.__init__r5   r+   c                 C   s   t || j| j| j| jS r-   )r6   rrelur[   r\   trainingr*   r7   r3   r3   r4   r8      s   zRReLU.forwardc                 C   r:   )Nr;   r<   zlower=z, upper=)r*   r[   r\   r=   r3   r3   r4   r?      r@   zRReLU.extra_repr)r]   r^   FrB   r3   r3   r1   r4   r      s    
 %r   c                       s   e Zd ZU dZg dZeed< eed< eed< 							ddededed
ee dee dd	f fddZ	de
de
fddZdefddZ  ZS )r   a  Applies the HardTanh function element-wise.

    HardTanh is defined as:

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

    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:`(*)`, where :math:`*` means any number of dimensions.
        - Output: :math:`(*)`, 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*   ra   rb   r*               ?FN	min_value	max_valuer+   c                    sh   t    |d urtjdtdd |}|d ur!tjdtdd |}|| _|| _|| _| j| jks2J d S )NzBkeyword argument `min_value` is deprecated and rename to `min_val`   )
stacklevelzBkeyword argument `max_value` is deprecated and rename to `max_val`)r.   r/   warningswarnFutureWarningra   rb   r*   )r0   ra   rb   r*   re   rf   r1   r3   r4   r/      s&   
zHardtanh.__init__r5   c                 C   s   t || j| j| jS r-   )r6   hardtanhra   rb   r*   r7   r3   r3   r4   r8     r9   zHardtanh.forwardc                 C   r:   )Nr;   r<   zmin_val=z
, max_val=)r*   ra   rb   r=   r3   r3   r4   r?     r@   zHardtanh.extra_repr)rc   rd   FNN)rC   rD   rE   rF   rG   rH   rI   rJ   r   r/   r   r8   rZ   r?   rK   r3   r3   r1   r4   r      s4   
  r   c                       s6   e Zd ZdZd	def fddZdefddZ  ZS )
r   a  Applies the ReLU6 function element-wise.

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

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

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

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

    Examples::

        >>> m = nn.ReLU6()
        >>> input = torch.randn(2)
        >>> output = m(input)
    Fr*   c                    s   t  dd| d S )N        g      @)r.   r/   rO   r1   r3   r4   r/   *     zReLU6.__init__r+   c                 C   rV   rW   rS   r=   r3   r3   r4   r?   -  rX   zReLU6.extra_reprrA   )	rC   rD   rE   rF   rJ   r/   rZ   r?   rK   r3   r3   r1   r4   r     s    r   c                   @   "   e Zd ZdZdedefddZdS )r   a  Applies the Sigmoid function element-wise.

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


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

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

    Examples::

        >>> m = nn.Sigmoid()
        >>> input = torch.randn(2)
        >>> output = m(input)
    r5   r+   c                 C   
   t |S r-   )torchsigmoidr7   r3   r3   r4   r8   F     
zSigmoid.forwardNrC   rD   rE   rF   r   r8   r3   r3   r3   r4   r   2  s    r   c                       N   e Zd ZU dZdgZeed< ddeddf fddZdedefd	d
Z	  Z
S )r   a  Applies the Hardsigmoid function element-wise.

    Hardsigmoid is defined as:

    .. 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:`(*)`, where :math:`*` means any number of dimensions.
        - Output: :math:`(*)`, same shape as the input.

    .. image:: ../scripts/activation_images/Hardsigmoid.png

    Examples::

        >>> m = nn.Hardsigmoid()
        >>> input = torch.randn(2)
        >>> output = m(input)
    r*   Fr+   Nc                    rM   r-   rN   rO   r1   r3   r4   r/   j  rP   zHardsigmoid.__init__r5   c                 C      t || jS r-   )r6   hardsigmoidr*   r7   r3   r3   r4   r8   n     zHardsigmoid.forwardrA   rC   rD   rE   rF   rG   rJ   rI   r/   r   r8   rK   r3   r3   r1   r4   r   J  s   
 r   c                   @   ro   )r   a  Applies the Hyperbolic Tangent (Tanh) function element-wise.

    Tanh is defined as:

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

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

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

    Examples::

        >>> m = nn.Tanh()
        >>> input = torch.randn(2)
        >>> output = m(input)
    r5   r+   c                 C   rp   r-   )rq   tanhr7   r3   r3   r4   r8     rs   zTanh.forwardNrt   r3   r3   r3   r4   r   r  s    r   c                       rL   )r   a  Applies the Sigmoid Linear Unit (SiLU) function, element-wise.

    The SiLU function is also known as the swish function.

    .. 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:`(*)`, where :math:`*` means any number of dimensions.
        - Output: :math:`(*)`, same shape as the input.

    .. image:: ../scripts/activation_images/SiLU.png

    Examples::

        >>> m = nn.SiLU()
        >>> input = torch.randn(2)
        >>> output = m(input)
    r*   Fc                    rM   r-   rN   rO   r1   r3   r4   r/     rP   zSiLU.__init__r5   r+   c                 C   rQ   rR   )r6   silur*   r7   r3   r3   r4   r8     rU   zSiLU.forwardc                 C   rV   rW   rS   r=   r3   r3   r4   r?     rX   zSiLU.extra_reprrA   rY   r3   r3   r1   r4   r     s   
 r   c                       rL   )r   ax  Applies the Mish function, element-wise.

    Mish: A Self Regularized Non-Monotonic Neural Activation Function.

    .. math::
        \text{Mish}(x) = x * \text{Tanh}(\text{Softplus}(x))

    .. note::
        See `Mish: A Self Regularized Non-Monotonic Neural Activation Function <https://arxiv.org/abs/1908.08681>`_

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

    .. image:: ../scripts/activation_images/Mish.png

    Examples::

        >>> m = nn.Mish()
        >>> input = torch.randn(2)
        >>> output = m(input)
    r*   Fc                    rM   r-   rN   rO   r1   r3   r4   r/     rP   zMish.__init__r5   r+   c                 C   rQ   rR   )r6   mishr*   r7   r3   r3   r4   r8     rU   zMish.forwardc                 C   rV   rW   rS   r=   r3   r3   r4   r?     rX   zMish.extra_reprrA   rY   r3   r3   r1   r4   r     s   
 r   c                       ru   )r   a  Applies the Hardswish function, element-wise.

    Method described in the paper: `Searching for MobileNetV3 <https://arxiv.org/abs/1905.02244>`_.

    Hardswish is defined as:

    .. 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:`(*)`, where :math:`*` means any number of dimensions.
        - Output: :math:`(*)`, same shape as the input.

    .. image:: ../scripts/activation_images/Hardswish.png

    Examples::

        >>> m = nn.Hardswish()
        >>> input = torch.randn(2)
        >>> output = m(input)
    r*   Fr+   Nc                    rM   r-   rN   rO   r1   r3   r4   r/      rP   zHardswish.__init__r5   c                 C   rv   r-   )r6   	hardswishr*   r7   r3   r3   r4   r8     rx   zHardswish.forwardrA   ry   r3   r3   r1   r4   r     s   
 r   c                       j   e Zd ZU dZddgZeed< eed< ddededdf fdd	Zd
e	de	fddZ
defddZ  ZS )r   as  Applies the Exponential Linear Unit (ELU) function, element-wise.

    Method described in the paper: `Fast and Accurate Deep Network Learning by Exponential Linear
    Units (ELUs) <https://arxiv.org/abs/1511.07289>`__.

    ELU is defined as:

    .. 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:`(*)`, where :math:`*` means any number of dimensions.
        - Output: :math:`(*)`, same shape as the input.

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

    Examples::

        >>> m = nn.ELU()
        >>> input = torch.randn(2)
        >>> output = m(input)
    alphar*   rd   Fr+   Nc                       t    || _|| _d S r-   r.   r/   r   r*   r0   r   r*   r1   r3   r4   r/   +     

zELU.__init__r5   c                 C      t || j| jS r-   )r6   elur   r*   r7   r3   r3   r4   r8   0     zELU.forwardc                 C      | j rdnd}d| j | S Nr;   r<   zalpha=r*   r   r=   r3   r3   r4   r?   3     zELU.extra_reprrd   FrC   rD   rE   rF   rG   rH   rI   rJ   r/   r   r8   rZ   r?   rK   r3   r3   r1   r4   r     s   
 r   c                       r~   )r   a3  Applies the CELU function element-wise.

    .. 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:`(*)`, where :math:`*` means any number of dimensions.
        - Output: :math:`(*)`, 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
    r   r*   rd   Fr+   Nc                    r   r-   r   r   r1   r3   r4   r/   X  r   zCELU.__init__r5   c                 C   r   r-   )r6   celur   r*   r7   r3   r3   r4   r8   ]  r   zCELU.forwardc                 C   r   r   r   r=   r3   r3   r4   r?   `  r   zCELU.extra_reprr   r   r3   r3   r1   r4   r   8  s   
 r   c                       \   e Zd ZU dZdgZeed< ddeddf fddZdedefd	d
Z	de
fddZ  ZS )r   a  Applies the SELU function element-wise.

    .. 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`.

    .. warning::
        When using ``kaiming_normal`` or ``kaiming_normal_`` for initialisation,
        ``nonlinearity='linear'`` should be used instead of ``nonlinearity='selu'``
        in order to get `Self-Normalizing Neural Networks`_.
        See :func:`torch.nn.init.calculate_gain` for more information.

    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:`(*)`, where :math:`*` means any number of dimensions.
        - Output: :math:`(*)`, 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*   Fr+   Nc                    rM   r-   rN   rO   r1   r3   r4   r/     rP   zSELU.__init__r5   c                 C   rv   r-   )r6   selur*   r7   r3   r3   r4   r8     rx   zSELU.forwardc                 C   rV   rW   rS   r=   r3   r3   r4   r?     rX   zSELU.extra_reprrA   rY   r3   r3   r1   r4   r   e  s   
 "r   c                       r   )r   a5  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)
    dimr+   Nc                    rM   r-   r.   r/   r   r0   r   r1   r3   r4   r/     rP   zGLU.__init__r5   c                 C   rv   r-   )r6   glur   r7   r3   r3   r4   r8     rx   zGLU.forwardc                 C      d| j  S Nzdim=r   r0   r3   r3   r4   r?        zGLU.extra_repr)r   )rC   rD   rE   rF   rG   intrI   r/   r   r8   rZ   r?   rK   r3   r3   r1   r4   r     s   
 r   c                       s\   e Zd ZU dZdgZeed< ddeddf fddZdedefd	d
Z	defddZ
  ZS )r   a/  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.

    When the approximate argument is 'tanh', Gelu is estimated with:

    .. math:: \text{GELU}(x) = 0.5 * x * (1 + \text{Tanh}(\sqrt{2 / \pi} * (x + 0.044715 * x^3)))

    Args:
        approximate (str, optional): the gelu approximation algorithm to use:
            ``'none'`` | ``'tanh'``. Default: ``'none'``

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

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

    Examples::

        >>> m = nn.GELU()
        >>> input = torch.randn(2)
        >>> output = m(input)
    approximatenoner+   Nc                    rM   r-   )r.   r/   r   )r0   r   r1   r3   r4   r/     rP   zGELU.__init__r5   c                 C   rQ   )N)r   )r6   gelur   r7   r3   r3   r4   r8     rU   zGELU.forwardc                 C   s   dt | j S )Nzapproximate=)reprr   r   r3   r3   r4   r?     rU   zGELU.extra_repr)r   )rC   rD   rE   rF   rG   rZ   rI   r/   r   r8   r?   rK   r3   r3   r1   r4   r     s   
 r   c                       r   )r   a  Applies the Hard Shrinkage (Hardshrink) function element-wise.

    Hardshrink is defined as:

    .. 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:`(*)`, where :math:`*` means any number of dimensions.
        - Output: :math:`(*)`, same shape as the input.

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

    Examples::

        >>> m = nn.Hardshrink()
        >>> input = torch.randn(2)
        >>> output = m(input)
    lambd      ?r+   Nc                    rM   r-   r.   r/   r   r0   r   r1   r3   r4   r/     rP   zHardshrink.__init__r5   c                 C   rv   r-   )r6   
hardshrinkr   r7   r3   r3   r4   r8     rx   zHardshrink.forwardc                 C   s   | j  S r-   )r   r   r3   r3   r4   r?     s   zHardshrink.extra_reprr   rC   rD   rE   rF   rG   rH   rI   r/   r   r8   rZ   r?   rK   r3   r3   r1   r4   r     s   
 r   c                       sj   e Zd ZU dZddgZeed< eed< ddededdf fdd	Zd
e	de	fddZ
defddZ  ZS )r   a}  Applies the LeakyReLU function element-wise.

    .. 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 (which is used for
          negative input values). Default: 1e-2
        inplace: can optionally do the operation in-place. Default: ``False``

    Shape:
        - Input: :math:`(*)` where `*` means, any number of additional
          dimensions
        - Output: :math:`(*)`, 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{Gz?Fr+   Nc                    r   r-   )r.   r/   r   r*   )r0   r   r*   r1   r3   r4   r/   6  r   zLeakyReLU.__init__r5   c                 C   r   r-   )r6   
leaky_relur   r*   r7   r3   r3   r4   r8   ;  r   zLeakyReLU.forwardc                 C   r   )Nr;   r<   znegative_slope=)r*   r   r=   r3   r3   r4   r?   >  r   zLeakyReLU.extra_repr)r   F)rC   rD   rE   rF   rG   rJ   rI   rH   r/   r   r8   rZ   r?   rK   r3   r3   r1   r4   r     s   
 "r   c                   @   ro   )r   a  Applies the Logsigmoid function element-wise.

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

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

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

    Examples::

        >>> m = nn.LogSigmoid()
        >>> input = torch.randn(2)
        >>> output = m(input)
    r5   r+   c                 C   rp   r-   )r6   
logsigmoidr7   r3   r3   r4   r8   V  rs   zLogSigmoid.forwardNrt   r3   r3   r3   r4   r   C      r   c                       sj   e Zd ZU dZddgZeed< eed< ddededdf fdd	Zd
edefddZ	de
fddZ  ZS )r   ay  Applies the Softplus function element-wise.

    .. 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:`(*)`, where :math:`*` means any number of dimensions.
        - Output: :math:`(*)`, same shape as the input.

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

    Examples::

        >>> m = nn.Softplus()
        >>> input = torch.randn(2)
        >>> output = m(input)
    betar(   rd         4@r+   Nc                    r   r-   )r.   r/   r   r(   )r0   r   r(   r1   r3   r4   r/   {  r   zSoftplus.__init__r5   c                 C   r   r-   )r6   softplusr   r(   r7   r3   r3   r4   r8     r   zSoftplus.forwardc                 C   s   d| j  d| j S )Nzbeta=z, threshold=)r   r(   r   r3   r3   r4   r?     rn   zSoftplus.extra_repr)rd   r   r   r3   r3   r1   r4   r   Z  s   
 r   c                       r   )r   a  Applies the soft shrinkage function element-wise.

    .. 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:`(*)`, where :math:`*` means any number of dimensions.
        - Output: :math:`(*)`, same shape as the input.

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

    Examples::

        >>> m = nn.Softshrink()
        >>> input = torch.randn(2)
        >>> output = m(input)
    r   r   r+   Nc                    rM   r-   r   r   r1   r3   r4   r/     rP   zSoftshrink.__init__r5   c                 C   rv   r-   )r6   
softshrinkr   r7   r3   r3   r4   r8     rx   zSoftshrink.forwardc                 C   s
   t | jS r-   )rZ   r   r   r3   r3   r4   r?     rs   zSoftshrink.extra_reprr   r   r3   r3   r1   r4   r     s   
 r   xr+   c                 C   s$   | d ur| j jddtjjjfv S dS )NcpucudaT)devicetyperq   utilsbackend_registration_privateuse1_backend_namer   r3   r3   r4   _check_arg_device  s   r   c                 C   s   | d ur| j S dS )NF)requires_gradr   r3   r3   r4   _arg_requires_grad  s   r   c                  C   s,   t j st jj } tdd | D S dS )Nc                 s   s$    | ]}t |tjjjjkV  qd S r-   )r   rq   fxexperimentalproxy_tensorProxyTorchDispatchMode.0r   r3   r3   r4   	<genexpr>  s
    
z&_is_make_fx_tracing.<locals>.<genexpr>F)rq   jitis_scriptingr   _python_dispatch _get_current_dispatch_mode_stackany)torch_dispatch_mode_stackr3   r3   r4   _is_make_fx_tracing  s   

r   c                       s   e Zd ZU dZdgZeej ed< eej ed< 									d	d fd
dZ	dd Z
 fddZ					ddedededee dedee deded	eeee f fddZdee dee ded	eee ee f fddZ  ZS )r    a  Allows the model to jointly attend to information from different representation subspaces.

    .. note::
        See `this tutorial <https://pytorch.org/tutorials/intermediate/transformer_building_blocks.html>`_
        for an in depth discussion of the performant building blocks PyTorch offers for building your own
        transformer layers.

    Method described in the paper:
    `Attention Is All You Need <https://arxiv.org/abs/1706.03762>`_.

    Multi-Head Attention is defined as:

    .. math::
        \text{MultiHead}(Q, K, V) = \text{Concat}(\text{head}_1,\dots,\text{head}_h)W^O

    where :math:`\text{head}_i = \text{Attention}(QW_i^Q, KW_i^K, VW_i^V)`.

    ``nn.MultiheadAttention`` will use the optimized implementations of
    ``scaled_dot_product_attention()`` when possible.

    In addition to support for the new ``scaled_dot_product_attention()``
    function, for speeding up Inference, MHA will use
    fastpath inference with support for Nested Tensors, iff:

    - self attention is being computed (i.e., ``query``, ``key``, and ``value`` are the same tensor).
    - inputs are batched (3D) with ``batch_first==True``
    - Either autograd is disabled (using ``torch.inference_mode`` or ``torch.no_grad``) or no tensor argument ``requires_grad``
    - training is disabled (using ``.eval()``)
    - ``add_bias_kv`` is ``False``
    - ``add_zero_attn`` is ``False``
    - ``kdim`` and ``vdim`` are equal to ``embed_dim``
    - if a `NestedTensor <https://pytorch.org/docs/stable/nested.html>`_ is passed, neither ``key_padding_mask``
      nor ``attn_mask`` is passed
    - autocast is disabled

    If the optimized inference fastpath implementation is in use, a
    `NestedTensor <https://pytorch.org/docs/stable/nested.html>`_ can be passed for
    ``query``/``key``/``value`` to represent padding more efficiently than using a
    padding mask. In this case, a `NestedTensor <https://pytorch.org/docs/stable/nested.html>`_
    will be returned, and an additional speedup proportional to the fraction of the input
    that is padding can be expected.

    Args:
        embed_dim: Total dimension of the model.
        num_heads: Number of parallel attention heads. Note that ``embed_dim`` will be split
            across ``num_heads`` (i.e. each head will have dimension ``embed_dim // num_heads``).
        dropout: Dropout probability on ``attn_output_weights``. Default: ``0.0`` (no dropout).
        bias: If specified, adds bias to input / output projection layers. Default: ``True``.
        add_bias_kv: If specified, adds bias to the key and value sequences at dim=0. Default: ``False``.
        add_zero_attn: If specified, adds a new batch of zeros to the key and value sequences at dim=1.
            Default: ``False``.
        kdim: Total number of features for keys. Default: ``None`` (uses ``kdim=embed_dim``).
        vdim: Total number of features for values. Default: ``None`` (uses ``vdim=embed_dim``).
        batch_first: If ``True``, then the input and output tensors are provided
            as (batch, seq, feature). Default: ``False`` (seq, batch, feature).

    Examples::

        >>> # xdoctest: +SKIP
        >>> multihead_attn = nn.MultiheadAttention(embed_dim, num_heads)
        >>> attn_output, attn_output_weights = multihead_attn(query, key, value)

    .. _`FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness`:
         https://arxiv.org/abs/2205.14135

    batch_firstbias_kbias_vrm   TFNr+   c                    s  |dks|dkrt d| d| d|
|d}t   || _|d ur&|n|| _|d ur/|n|| _| j|ko;| j|k| _|| _|| _|	| _	|| | _
| j
| | jksWJ d| jsttj||ffi || _ttj|| jffi || _ttj|| jffi || _| dd  n"ttjd| |ffi || _| d	d  | d
d  | dd  |rttjd| fi || _n| dd  t||fd|i|| _|rttjdd|ffi || _ttjdd|ffi || _nd  | _| _|| _|   d S )Nr   z>embed_dim and num_heads must be greater than 0, got embed_dim=z and num_heads=z insteadr   dtypez(embed_dim must be divisible by num_headsin_proj_weight   q_proj_weightk_proj_weightv_proj_weightin_proj_biasbiasr   )
ValueErrorr.   r/   	embed_dimkdimvdim_qkv_same_embed_dim	num_headsdropoutr   head_dimr   rq   emptyr   r   r   register_parameterr   r   r	   out_projr   r   add_zero_attn_reset_parameters)r0   r   r   r   r   add_bias_kvr   r   r   r   r   r   factory_kwargsr1   r3   r4   r/     sl   


 zMultiheadAttention.__init__c                 C   s   | j r	t| j nt| j t| j t| j | jd ur*t| jd t| jj	d | j
d ur4t| j
 | jd ur@t| j d S d S )Nrm   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   r3   r3   r4   r   \  s   






z$MultiheadAttention._reset_parametersc                    s    d|vrd|d< t  | d S )Nr   T)r.   __setstate__r0   stater1   r3   r4   r   l  s   zMultiheadAttention.__setstate__querykeyr)   key_padding_maskneed_weights	attn_maskaverage_attn_weights	is_causalc	                 C   s  d}	|durt |s|durt |rd}	| dk}
tj|dt|d|jd}tj|ddd|jdd	}t jj	 }|sAd
}	n|
sKd|  }	n||usS||urVd}	n{| j
duro|j| j
jkrod|j d| j
j d}	nb| jdu rwd}	nZ|j| jjkrd|j d| jj d}	nF| jrd}	n@| jd dkrd}	n6| jsd}	n0| jdurd}	n(| jdurd}	n | jrd}	n| jsd}	n|jr|dus|durd}	nt  rd}	|	sG|||| j| j
| jj| jjf}t j|rd}	n*t rd}	n$tdd  |D sd!t jjj }	nt  rt d"d  |D rd#}	|	sG| !|||\}}| j
durG| jdurGt "|||| j#| j| j| j
| jj| jj||||S |jpQ|jpQ|j}|r^J d$d%|	  | jr|
r||u r||u rz|$d&d } }}nd'd  ||fD \}}|}nd(d  |||fD \}}}| jstj%|||| j#| j| j| j
| j| j| j| j&| jj| jjf| j|||d)| j'| j(| j)||d*
\}}n'tj%|||| j#| j| j| j
| j| j| j| j&| jj| jj| j|||||d+\}}| jr |
r |$d&d|fS ||fS ),aI  Compute attention outputs using query, key, and value embeddings.

            Supports optional parameters for padding, masks and attention weights.

        Args:
            query: Query embeddings of shape :math:`(L, E_q)` for unbatched input, :math:`(L, N, E_q)` when ``batch_first=False``
                or :math:`(N, L, E_q)` when ``batch_first=True``, where :math:`L` is the target sequence length,
                :math:`N` is the batch size, and :math:`E_q` is the query embedding dimension ``embed_dim``.
                Queries are compared against key-value pairs to produce the output.
                See "Attention Is All You Need" for more details.
            key: Key embeddings of shape :math:`(S, E_k)` for unbatched input, :math:`(S, N, E_k)` when ``batch_first=False``
                or :math:`(N, S, E_k)` when ``batch_first=True``, where :math:`S` is the source sequence length,
                :math:`N` is the batch size, and :math:`E_k` is the key embedding dimension ``kdim``.
                See "Attention Is All You Need" for more details.
            value: Value embeddings of shape :math:`(S, E_v)` for unbatched input, :math:`(S, N, E_v)` when
                ``batch_first=False`` or :math:`(N, S, E_v)` when ``batch_first=True``, where :math:`S` is the source
                sequence length, :math:`N` is the batch size, and :math:`E_v` is the value embedding dimension ``vdim``.
                See "Attention Is All You Need" for more details.
            key_padding_mask: If specified, a mask of shape :math:`(N, S)` indicating which elements within ``key``
                to ignore for the purpose of attention (i.e. treat as "padding"). For unbatched `query`, shape should be :math:`(S)`.
                Binary and float masks are supported.
                For a binary mask, a ``True`` value indicates that the corresponding ``key`` value will be ignored for
                the purpose of attention. For a float mask, it will be directly added to the corresponding ``key`` value.
            need_weights: If specified, returns ``attn_output_weights`` in addition to ``attn_outputs``.
                Set ``need_weights=False`` to use the optimized ``scaled_dot_product_attention``
                and achieve the best performance for MHA.
                Default: ``True``.
            attn_mask: If specified, a 2D or 3D mask preventing attention to certain positions. Must be of shape
                :math:`(L, S)` or :math:`(N\cdot\text{num\_heads}, L, S)`, where :math:`N` is the batch size,
                :math:`L` is the target sequence length, and :math:`S` is the source sequence length. A 2D mask will be
                broadcasted across the batch while a 3D mask allows for a different mask for each entry in the batch.
                Binary and float masks are supported. For a binary mask, a ``True`` value indicates that the
                corresponding position is not allowed to attend. For a float mask, the mask values will be added to
                the attention weight.
                If both attn_mask and key_padding_mask are supplied, their types should match.
            average_attn_weights: If true, indicates that the returned ``attn_weights`` should be averaged across
                heads. Otherwise, ``attn_weights`` are provided separately per head. Note that this flag only has an
                effect when ``need_weights=True``. Default: ``True`` (i.e. average weights across heads)
            is_causal: If specified, applies a causal mask as attention mask.
                Default: ``False``.
                Warning:
                ``is_causal`` provides a hint that ``attn_mask`` is the
                causal mask. Providing incorrect hints can result in
                incorrect execution, including forward and backward
                compatibility.

        Outputs:
            - **attn_output** - Attention outputs of shape :math:`(L, E)` when input is unbatched,
              :math:`(L, N, E)` when ``batch_first=False`` or :math:`(N, L, E)` when ``batch_first=True``,
              where :math:`L` is the target sequence length, :math:`N` is the batch size, and :math:`E` is the
              embedding dimension ``embed_dim``.
            - **attn_output_weights** - Only returned when ``need_weights=True``. If ``average_attn_weights=True``,
              returns attention weights averaged across heads of shape :math:`(L, S)` when input is unbatched or
              :math:`(N, L, S)`, where :math:`N` is the batch size, :math:`L` is the target sequence length, and
              :math:`S` is the source sequence length. If ``average_attn_weights=False``, returns attention weights per
              head of shape :math:`(\text{num\_heads}, L, S)` when input is unbatched or :math:`(N, \text{num\_heads}, L, S)`.

            .. note::
                `batch_first` argument is ignored for unbatched inputs.
        r<   Nz5floating-point masks are not supported for fast path.r   r   r   )mask	mask_name
other_type
other_nametarget_typeF)r   r   r   r   r   check_otherz6torch.backends.mha.get_fastpath_enabled() was not Truez5input not batched; expected query.dim() of 3 but got zKnon-self attention was used (query, key, and value are not the same Tensor)zdtypes of query (z) and self.in_proj_bias (z) don't matchzin_proj_weight was Nonez) and self.in_proj_weight (ztraining is enabledrg   r   zself.num_heads is not evenzbatch_first was not Truezself.bias_k was not Nonezself.bias_v was not Nonezadd_zero_attn was enabledz _qkv_same_embed_dim was not Truezsupplying both src_key_padding_mask and src_mask at the same time                                  is not supported with NestedTensor inputzautocast is enabledz'some Tensor argument has_torch_functionzwe are running make_fx tracingc                 s       | ]}t |V  qd S r-   )r   r   r3   r3   r4   r     s    z-MultiheadAttention.forward.<locals>.<genexpr>z=some Tensor argument's device is neither one of cpu, cuda or c                 s   r   r-   )r   r   r3   r3   r4   r     s    
zhgrad is enabled and at least one of query or the input/output projection weights or biases requires_gradzKMultiheadAttention does not support NestedTensor outside of its fast path. z"The fast path was not hit because r   c                 s       | ]	}| d dV  qdS r   r   N	transposer   r3   r3   r4   r   =      c                 s   r   r   r   r   r3   r3   r4   r   @  r   T)
r`   r   r   r   use_separate_proj_weightr   r   r   r   r   )r`   r   r   r   r   r   )*rq   is_floating_pointr   r6   _canonical_mask_none_or_dtyper   backendsmhaget_fastpath_enabledr   r   r`   r   r   r   r   r   r   	is_nestedis_autocast_enabledr   weightr   	overrideshas_torch_functionr   allr   r   r   is_grad_enabledr   merge_masks_native_multi_head_attentionr   r   multi_head_attention_forwardr   r   r   r   )r0   r   r   r)   r   r   r   r   r   why_not_fast_path
is_batchedis_fastpath_enabledtensor_argsmerged_mask	mask_type
any_nestedattn_outputattn_output_weightsr3   r3   r4   r8   s  sD  G	






zMultiheadAttention.forwardc                 C   s   d}d}|durd}|}|durO|j \}}}d}| dkr'||d||}	n|dd|||| jdd}	|	}|durO||dd|d| jdd}
|	|
 }||fS )a  Determine mask type and combine masks if necessary.

        If only one mask is provided, that mask
        and the corresponding mask type will be returned. If both masks are provided, they will be both
        expanded to shape ``(batch_size, num_heads, seq_len, seq_len)``, combined with logical ``or``
        and mask type 2 will be returned
        Args:
            attn_mask: attention mask of shape ``(seq_len, seq_len)``, mask type 0
            key_padding_mask: padding mask of shape ``(batch_size, seq_len)``, mask type 1
            query: query embeddings of shape ``(batch_size, seq_len, embed_dim)``
        Returns:
            merged_mask: merged mask
            mask_type: merged mask type (0, 1, or 2)
        Nr   rg   r   r   )shaper   viewexpandr   )r0   r   r   r   r  r  
batch_sizeseq_len_attn_mask_expandedkey_padding_mask_expandedr3   r3   r4   r  w  s,   
zMultiheadAttention.merge_masks)	rm   TFFNNFNN)r+   N)NTNTF)rC   rD   rE   rF   rG   r   rq   r   rI   r/   r   r   rJ   tupler8   r   r  rK   r3   r3   r1   r4   r      sl   
 CG	

  r    c                       sj   e Zd ZU dZdgZeed< 	ddededdf fdd	Zd
d Z	de
de
fddZdefddZ  ZS )r!   a  Applies the element-wise PReLU function.

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

    or

    .. math::
        \text{PReLU}(x) =
        \begin{cases}
        x, & \text{ if } x \ge 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:`( *)` where `*` means, any number of additional
          dimensions.
        - Output: :math:`(*)`, 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initr+   c                    sD   ||d}|| _ t   || _ttj|fi || _|   d S )Nr   )	r  r.   r/   r  r   rq   r   r  reset_parameters)r0   r  r  r   r   r   r1   r3   r4   r/     s   

zPReLU.__init__c                 C   s   t jj| j| j d S r-   )rq   nnr  r   r  r   r3   r3   r4   r     s   zPReLU.reset_parametersr5   c                 C   rv   r-   )r6   prelur  r7   r3   r3   r4   r8     rx   zPReLU.forwardc                 C   r   )Nznum_parameters=)r  r   r3   r3   r4   r?     r   zPReLU.extra_repr)r   r  NN)rC   rD   rE   rF   rG   r   rI   rH   r/   r   r   r8   rZ   r?   rK   r3   r3   r1   r4   r!     s   
 1
r!   c                   @   ro   )r"   a  Applies the element-wise Softsign function.

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

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

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

    Examples::

        >>> m = nn.Softsign()
        >>> input = torch.randn(2)
        >>> output = m(input)
    r5   r+   c                 C   rp   r-   )r6   softsignr7   r3   r3   r4   r8     rs   zSoftsign.forwardNrt   r3   r3   r3   r4   r"     r   r"   c                   @   ro   )r#   a  Applies the element-wise Tanhshrink function.

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

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

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

    Examples::

        >>> m = nn.Tanhshrink()
        >>> input = torch.randn(2)
        >>> output = m(input)
    r5   r+   c                 C   rp   r-   )r6   
tanhshrinkr7   r3   r3   r4   r8     rs   zTanhshrink.forwardNrt   r3   r3   r3   r4   r#   
  r   r#   c                       j   e Zd ZU dZdgZee ed< ddee ddf fddZ fddZ	d	e
de
fd
dZdd Z  ZS )r$   a:  Applies the Softmin function to an n-dimensional input Tensor.

    Rescales 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

    Args:
        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(dim=1)
        >>> input = torch.randn(2, 3)
        >>> output = m(input)
    r   Nr+   c                    rM   r-   r   r   r1   r3   r4   r/   C  rP   zSoftmin.__init__c                    $   t  | t| dsd | _d S d S Nr   r.   r   hasattrr   r   r1   r3   r4   r   G     

zSoftmin.__setstate__r5   c                 C      t j|| jddS N   _stacklevel)r6   softminr   r7   r3   r3   r4   r8   L  r   zSoftmin.forwardc                 C   r   r   r   r   r3   r3   r4   r?   O  r   zSoftmin.extra_reprr-   rC   rD   rE   rF   rG   r   r   rI   r/   r   r   r8   r?   rK   r3   r3   r1   r4   r$   !  s   
 r$   c                       sp   e Zd ZU dZdgZee ed< ddee ddf fddZ fddZ	d	e
de
fd
dZdefddZ  ZS )r%   a  Applies the Softmax function to an n-dimensional input Tensor.

    Rescales 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 unspecified
    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]

    Args:
        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                    rM   r-   r   r   r1   r3   r4   r/   ~  rP   zSoftmax.__init__c                    r&  r'  r(  r   r1   r3   r4   r     r*  zSoftmax.__setstate__r5   c                 C   r+  r,  )r6   softmaxr   r7   r3   r3   r4   r8     r   zSoftmax.forwardc                 C   r   r   r   r   r3   r3   r4   r?     r   zSoftmax.extra_reprr-   )rC   rD   rE   rF   rG   r   r   rI   r/   r   r   r8   rZ   r?   rK   r3   r3   r1   r4   r%   S  s   
 'r%   c                   @   ro   )r&   a|  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)` or :math:`(C, H, W)`.
        - Output: :math:`(N, C, H, W)` or :math:`(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)
    r5   r+   c                 C   s0   |  dvrtd|   dtj|dddS )N)r      z.Softmax2d: expected input to be 3D or 4D, got z	D insteadr-  r.  )r   r   r6   r2  r7   r3   r3   r4   r8     s
   zSoftmax2d.forwardNrt   r3   r3   r3   r4   r&     s    r&   c                       r%  )r'   a  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

    Args:
        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(dim=1)
        >>> input = torch.randn(2, 3)
        >>> output = m(input)
    r   Nr+   c                    rM   r-   r   r   r1   r3   r4   r/     rP   zLogSoftmax.__init__c                    r&  r'  r(  r   r1   r3   r4   r     r*  zLogSoftmax.__setstate__r5   c                 C   r+  r,  )r6   log_softmaxr   r7   r3   r3   r4   r8     r   zLogSoftmax.forwardc                 C   r   r   r   r   r3   r3   r4   r?     r   zLogSoftmax.extra_reprr-   r1  r3   r3   r1   r4   r'     s   
 r'   )5ri   typingr   rq   torch.nn.functionalr!  
functionalr6   r   torch.nn.initr   r   r   torch.nn.parameterr   linearr	   moduler
   __all__r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rJ   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r3   r3   r3   r4   <module>   sZ   !1+<L(,'*0-2#*+4-)
   `I2;