a
    ßñhˆ ã                   @   sä  d Z ddlZddlZddlZddlmZmZ ddlmZ	 ddl
mZ ddlmZmZmZmZ ddlmZ dd	lmZ d
dlmZmZmZmZmZ d
dlmZmZ ejZeejdƒZeejdƒZeejdƒZeej dƒZ eej!dƒZ!eej"dƒZ"eej#dƒZ#eej$dƒZ$eej%j&j'dƒZ'eej%j&j(dƒZ(�d$dd„Z)�d%dd„Z*eddde)e*e+dd�Z,�d&d d!„Z-�d'd"d#„Z.eddde-e.e+d$d�Z/�d(d%d&„Z0�d)d'd(„Z1edd)de0e1e+d*d�Z2�d*d+d,„Z3�d+d-d.„Z4edd)de3e4e+d/d�Z5�d,d0d1„Z6�d-d2d3„Z7edd)de6e7e+d4d�Z8d5d6„ Z9�d.d7d8„Z:�d/d9d:„Z;�d0d;d<„Z<�d1d=d>„Z=�d2d?d@„Z>�d3dAdB„Z?�d4dCdD„Z@edd
de?e@e+dEd�ZA�d5dFdG„ZB�d6dHdI„ZCedd
deBeCe+dJd�ZD�d7dKdL„ZE�d8dMdN„ZFedd
deEeFe+dOd�ZGeejHdPƒZHdQdR„ ZIdSdT„ ZJ�d9dWdX„ZK�d:dYdZ„ZL�d;d[d\„ZM�d<d]d^„ZN�d=d_d`„ZO�d>dadb„ZPePZQeejRdcƒZR�d?eeSeddœdedf„ZTeejUdgƒZU�d@eeVediœdjdk„ZW�dAeeXeXeSednœdodp„ZYeej%j&jZdqƒZZ�dBdrds„Z[�dCdtdu„Z\eej%j&j]dvƒZ]�dDdwdx„Z^eej_dyƒZ_�dEdzd{„Z`eejad|ƒZa�dFeeXeSed~œdd€„Zbeej%j&jcd�ƒZcd‚dƒ„ Zd�dGd†d‡„ZeeejfdˆƒZfeej%j&jgd‰ƒZhdŠd‹„ Zi�dHdŒd�„ZjdŽd�„ Zkd�d‘„ Zleej%j&jmd’ƒZmd“d”„ Zn�dId–d—„Zo�dJd˜d™„Zp�dKd›dœ„Zq�dLd�dž„Zreej%j&jsdŸƒZsd d¡„ Ztd¢d£„ Zu�dMd¤d¥„Zv�dNd¦d§„Zw�dOd¨d©„Zx�dPdªd«„Zy�dQeeSeddœd¬d­„Zzd®d¯„ Z{�dRd±d²„Z|�dSd´dµ„Z}d¶d·„ Z~�dTdºd»„Z�dUd¼d½„Z€�dVd¾d¿„Z��dWdÀdÁ„Z‚�dXdÄdÅ„Zƒ�dYdÆdÇ„Z„�dZdÉdÊ„Z…�d[dÌdÍ„Z†�d\dÎdÏ„Z‡�d]dÐdÑ„Zˆ�d^dÒdÓ„Z‰�d_dÔdÕ„ZŠ�d`dÖd×„Z‹�dadØdÙ„ZŒ�dbdÚdÛ„Z��dcdÜdÝ„ZŽ�dddÞdß„Z��dedàdá„Z��dfdâdã„Z‘�dgdädå„Z’�dhdædç„Z“�didèdé„Z”eej•dêƒZ•eej–dëƒZ–e�djdídî„ƒZ—e�dkdïdî„ƒZ—�dldðdî„Z—e�dmdñdò„ƒZ˜e�dndódò„ƒZ˜e�dodôdò„ƒZ˜e�dpdõdò„ƒZ˜�dqdödò„Z˜e�drd÷dø„ƒZ™e�dsdùdø„ƒZ™�dtdúdø„Z™e�dudûdü„ƒZše�dvdýdü„ƒZše�dwdþdü„ƒZše�dxdÿdü„ƒZš�dy�d dü„Zšdd�dœZ›ddd
�dœZœ�dz�d�d„Z��d{�d�d„Zž�d|�d	�d
„ZŸeŸZ �d}�d�d„Z¡eej¢�dƒZ¢eej£�dƒZ£eej%j&j¤�dƒZ¤�d~�d�d„Z¥ddmdd³�dœ�d�d„Z¦�d�d�d„Z§�d�d„ Z¨�d€�d�d„Z©�d��d�d„Zª�d�d „ Z«�d‚eeeeVeVeeee ee eSeXeeeSee eSee eSee ee ee ee ee eeee f �d!œ�d"�d#„Z¬dS (ƒ  zFunctional interfaceé    N)Ú_infer_sizeÚ_add_docstré   )Ú
_reduction)Úutils)Ú_singleÚ_pairÚ_tripleÚ_list_with_default)Úgrad)Ú_VFé   )Úboolean_dispatchÚListÚOptionalÚ	_overloadÚTuple)Úhas_torch_functionÚhandle_torch_functionaM  
conv1d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1) -> Tensor

Applies a 1D convolution over an input signal composed of several input
planes.

This operator supports :ref:`TensorFloat32<tf32_on_ampere>`.

See :class:`~torch.nn.Conv1d` for details and output shape.

Note:
    In some circumstances when using the CUDA backend with CuDNN, this operator
    may select a nondeterministic algorithm to increase performance. If this is
    undesirable, you can try to make the operation deterministic (potentially at
    a performance cost) by setting ``torch.backends.cudnn.deterministic =
    True``.
    Please see the notes on :doc:`/notes/randomness` for background.

Args:
    input: input tensor of shape :math:`(\text{minibatch} , \text{in\_channels} , iW)`
    weight: filters of shape :math:`(\text{out\_channels} , \frac{\text{in\_channels}}{\text{groups}} , kW)`
    bias: optional bias of shape :math:`(\text{out\_channels})`. Default: ``None``
    stride: the stride of the convolving kernel. Can be a single number or
      a one-element tuple `(sW,)`. Default: 1
    padding: implicit paddings on both sides of the input. Can be a
      single number or a one-element tuple `(padW,)`. Default: 0
    dilation: the spacing between kernel elements. Can be a single number or
      a one-element tuple `(dW,)`. Default: 1
    groups: split input into groups, :math:`\text{in\_channels}` should be divisible by
      the number of groups. Default: 1

Examples::

    >>> filters = torch.randn(33, 16, 3)
    >>> inputs = torch.randn(20, 16, 50)
    >>> F.conv1d(inputs, filters)
az  
conv2d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1) -> Tensor

Applies a 2D convolution over an input image composed of several input
planes.

This operator supports :ref:`TensorFloat32<tf32_on_ampere>`.

See :class:`~torch.nn.Conv2d` for details and output shape.

Note:
    In some circumstances when using the CUDA backend with CuDNN, this operator
    may select a nondeterministic algorithm to increase performance. If this is
    undesirable, you can try to make the operation deterministic (potentially at
    a performance cost) by setting ``torch.backends.cudnn.deterministic =
    True``.
    Please see the notes on :doc:`/notes/randomness` for background.


Args:
    input: input tensor of shape :math:`(\text{minibatch} , \text{in\_channels} , iH , iW)`
    weight: filters of shape :math:`(\text{out\_channels} , \frac{\text{in\_channels}}{\text{groups}} , kH , kW)`
    bias: optional bias tensor of shape :math:`(\text{out\_channels})`. Default: ``None``
    stride: the stride of the convolving kernel. Can be a single number or a
      tuple `(sH, sW)`. Default: 1
    padding: implicit paddings on both sides of the input. Can be a
      single number or a tuple `(padH, padW)`. Default: 0
    dilation: the spacing between kernel elements. Can be a single number or
      a tuple `(dH, dW)`. Default: 1
    groups: split input into groups, :math:`\text{in\_channels}` should be divisible by the
      number of groups. Default: 1

Examples::

    >>> # With square kernels and equal stride
    >>> filters = torch.randn(8,4,3,3)
    >>> inputs = torch.randn(1,4,5,5)
    >>> F.conv2d(inputs, filters, padding=1)
af  
conv3d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1) -> Tensor

Applies a 3D convolution over an input image composed of several input
planes.

This operator supports :ref:`TensorFloat32<tf32_on_ampere>`.

See :class:`~torch.nn.Conv3d` for details and output shape.

Note:
    In some circumstances when using the CUDA backend with CuDNN, this operator
    may select a nondeterministic algorithm to increase performance. If this is
    undesirable, you can try to make the operation deterministic (potentially at
    a performance cost) by setting ``torch.backends.cudnn.deterministic =
    True``.
    Please see the notes on :doc:`/notes/randomness` for background.

Args:
    input: input tensor of shape :math:`(\text{minibatch} , \text{in\_channels} , iT , iH , iW)`
    weight: filters of shape :math:`(\text{out\_channels} , \frac{\text{in\_channels}}{\text{groups}} , kT , kH , kW)`
    bias: optional bias tensor of shape :math:`(\text{out\_channels})`. Default: None
    stride: the stride of the convolving kernel. Can be a single number or a
      tuple `(sT, sH, sW)`. Default: 1
    padding: implicit paddings on both sides of the input. Can be a
      single number or a tuple `(padT, padH, padW)`. Default: 0
    dilation: the spacing between kernel elements. Can be a single number or
      a tuple `(dT, dH, dW)`. Default: 1
    groups: split input into groups, :math:`\text{in\_channels}` should be divisible by
      the number of groups. Default: 1

Examples::

    >>> filters = torch.randn(33, 16, 3, 3, 3)
    >>> inputs = torch.randn(20, 16, 50, 10, 20)
    >>> F.conv3d(inputs, filters)
a�  
conv_transpose1d(input, weight, bias=None, stride=1, padding=0, output_padding=0, groups=1, dilation=1) -> Tensor

Applies a 1D transposed convolution operator over an input signal
composed of several input planes, sometimes also called "deconvolution".

This operator supports :ref:`TensorFloat32<tf32_on_ampere>`.

See :class:`~torch.nn.ConvTranspose1d` for details and output shape.

Note:
    In some circumstances when using the CUDA backend with CuDNN, this operator
    may select a nondeterministic algorithm to increase performance. If this is
    undesirable, you can try to make the operation deterministic (potentially at
    a performance cost) by setting ``torch.backends.cudnn.deterministic =
    True``.
    Please see the notes on :doc:`/notes/randomness` for background.

Args:
    input: input tensor of shape :math:`(\text{minibatch} , \text{in\_channels} , iW)`
    weight: filters of shape :math:`(\text{in\_channels} , \frac{\text{out\_channels}}{\text{groups}} , kW)`
    bias: optional bias of shape :math:`(\text{out\_channels})`. Default: None
    stride: the stride of the convolving kernel. Can be a single number or a
      tuple ``(sW,)``. Default: 1
    padding: ``dilation * (kernel_size - 1) - padding`` zero-padding will be added to both
      sides of each dimension in the input. Can be a single number or a tuple
      ``(padW,)``. Default: 0
    output_padding: additional size added to one side of each dimension in the
      output shape. Can be a single number or a tuple ``(out_padW)``. Default: 0
    groups: split input into groups, :math:`\text{in\_channels}` should be divisible by the
      number of groups. Default: 1
    dilation: the spacing between kernel elements. Can be a single number or
      a tuple ``(dW,)``. Default: 1

Examples::

    >>> inputs = torch.randn(20, 16, 50)
    >>> weights = torch.randn(16, 33, 5)
    >>> F.conv_transpose1d(inputs, weights)
aà  
conv_transpose2d(input, weight, bias=None, stride=1, padding=0, output_padding=0, groups=1, dilation=1) -> Tensor

Applies a 2D transposed convolution operator over an input image
composed of several input planes, sometimes also called "deconvolution".

This operator supports :ref:`TensorFloat32<tf32_on_ampere>`.

See :class:`~torch.nn.ConvTranspose2d` for details and output shape.

Note:
    In some circumstances when using the CUDA backend with CuDNN, this operator
    may select a nondeterministic algorithm to increase performance. If this is
    undesirable, you can try to make the operation deterministic (potentially at
    a performance cost) by setting ``torch.backends.cudnn.deterministic =
    True``.
    Please see the notes on :doc:`/notes/randomness` for background.

Args:
    input: input tensor of shape :math:`(\text{minibatch} , \text{in\_channels} , iH , iW)`
    weight: filters of shape :math:`(\text{in\_channels} , \frac{\text{out\_channels}}{\text{groups}} , kH , kW)`
    bias: optional bias of shape :math:`(\text{out\_channels})`. Default: None
    stride: the stride of the convolving kernel. Can be a single number or a
      tuple ``(sH, sW)``. Default: 1
    padding: ``dilation * (kernel_size - 1) - padding`` zero-padding will be added to both
      sides of each dimension in the input. Can be a single number or a tuple
      ``(padH, padW)``. Default: 0
    output_padding: additional size added to one side of each dimension in the
      output shape. Can be a single number or a tuple ``(out_padH, out_padW)``.
      Default: 0
    groups: split input into groups, :math:`\text{in\_channels}` should be divisible by the
      number of groups. Default: 1
    dilation: the spacing between kernel elements. Can be a single number or
      a tuple ``(dH, dW)``. Default: 1

Examples::

    >>> # With square kernels and equal stride
    >>> inputs = torch.randn(1, 4, 5, 5)
    >>> weights = torch.randn(4, 8, 3, 3)
    >>> F.conv_transpose2d(inputs, weights, padding=1)
aÒ  
conv_transpose3d(input, weight, bias=None, stride=1, padding=0, output_padding=0, groups=1, dilation=1) -> Tensor

Applies a 3D transposed convolution operator over an input image
composed of several input planes, sometimes also called "deconvolution"

This operator supports :ref:`TensorFloat32<tf32_on_ampere>`.

See :class:`~torch.nn.ConvTranspose3d` for details and output shape.

Note:
    In some circumstances when using the CUDA backend with CuDNN, this operator
    may select a nondeterministic algorithm to increase performance. If this is
    undesirable, you can try to make the operation deterministic (potentially at
    a performance cost) by setting ``torch.backends.cudnn.deterministic =
    True``.
    Please see the notes on :doc:`/notes/randomness` for background.

Args:
    input: input tensor of shape :math:`(\text{minibatch} , \text{in\_channels} , iT , iH , iW)`
    weight: filters of shape :math:`(\text{in\_channels} , \frac{\text{out\_channels}}{\text{groups}} , kT , kH , kW)`
    bias: optional bias of shape :math:`(\text{out\_channels})`. Default: None
    stride: the stride of the convolving kernel. Can be a single number or a
      tuple ``(sT, sH, sW)``. Default: 1
    padding: ``dilation * (kernel_size - 1) - padding`` zero-padding will be added to both
      sides of each dimension in the input. Can be a single number or a tuple
      ``(padT, padH, padW)``. Default: 0
    output_padding: additional size added to one side of each dimension in the
      output shape. Can be a single number or a tuple
      ``(out_padT, out_padH, out_padW)``. Default: 0
    groups: split input into groups, :math:`\text{in\_channels}` should be divisible by the
      number of groups. Default: 1
    dilation: the spacing between kernel elements. Can be a single number or
      a tuple `(dT, dH, dW)`. Default: 1

Examples::

    >>> inputs = torch.randn(20, 16, 50, 10, 20)
    >>> weights = torch.randn(16, 33, 3, 3, 3)
    >>> F.conv_transpose3d(inputs, weights)
aÔ  
Applies a 1-dimensional sequence convolution over an input sequence.
Input and output dimensions are (Time, Batch, Channels) - hence TBC.

Args:
    input: input tensor of shape :math:`(\text{sequence length} \times batch \times \text{in\_channels})`
    weight: filter of shape (:math:`\text{kernel width} \times \text{in\_channels} \times \text{out\_channels}`)
    bias: bias of shape (:math:`\text{out\_channels}`)
    pad: number of timesteps to pad. Default: 0
az  
avg_pool1d(input, kernel_size, stride=None, padding=0, ceil_mode=False, count_include_pad=True) -> Tensor

Applies a 1D average pooling over an input signal composed of several
input planes.

See :class:`~torch.nn.AvgPool1d` for details and output shape.

Args:
    input: input tensor of shape :math:`(\text{minibatch} , \text{in\_channels} , iW)`
    kernel_size: the size of the window. Can be a single number or a
      tuple `(kW,)`
    stride: the stride of the window. Can be a single number or a tuple
      `(sW,)`. Default: :attr:`kernel_size`
    padding: implicit zero paddings on both sides of the input. Can be a
      single number or a tuple `(padW,)`. Default: 0
    ceil_mode: when True, will use `ceil` instead of `floor` to compute the
        output shape. Default: ``False``
    count_include_pad: when True, will include the zero-padding in the
        averaging calculation. Default: ``True``

Examples::

    >>> # pool of square window of size=3, stride=2
    >>> input = torch.tensor([[[1, 2, 3, 4, 5, 6, 7]]], dtype=torch.float32)
    >>> F.avg_pool1d(input, kernel_size=3, stride=2)
    tensor([[[ 2.,  4.,  6.]]])

a¸  
avg_pool2d(input, kernel_size, stride=None, padding=0, ceil_mode=False, count_include_pad=True, divisor_override=None) -> Tensor

Applies 2D average-pooling operation in :math:`kH \times kW` regions by step size
:math:`sH \times sW` steps. The number of output features is equal to the number of
input planes.

See :class:`~torch.nn.AvgPool2d` for details and output shape.

Args:
    input: input tensor :math:`(\text{minibatch} , \text{in\_channels} , iH , iW)`
    kernel_size: size of the pooling region. Can be a single number or a
      tuple `(kH, kW)`
    stride: stride of the pooling operation. Can be a single number or a
      tuple `(sH, sW)`. Default: :attr:`kernel_size`
    padding: implicit zero paddings on both sides of the input. Can be a
      single number or a tuple `(padH, padW)`. Default: 0
    ceil_mode: when True, will use `ceil` instead of `floor` in the formula
        to compute the output shape. Default: ``False``
    count_include_pad: when True, will include the zero-padding in the
        averaging calculation. Default: ``True``
    divisor_override: if specified, it will be used as divisor, otherwise
         size of the pooling region will be used. Default: None
aÖ  
avg_pool3d(input, kernel_size, stride=None, padding=0, ceil_mode=False, count_include_pad=True, divisor_override=None) -> Tensor

Applies 3D average-pooling operation in :math:`kT \times kH \times kW` regions by step
size :math:`sT \times sH \times sW` steps. The number of output features is equal to
:math:`\lfloor\frac{\text{input planes}}{sT}\rfloor`.

See :class:`~torch.nn.AvgPool3d` for details and output shape.

Args:
    input: input tensor :math:`(\text{minibatch} , \text{in\_channels} , iT \times iH , iW)`
    kernel_size: size of the pooling region. Can be a single number or a
      tuple `(kT, kH, kW)`
    stride: stride of the pooling operation. Can be a single number or a
      tuple `(sT, sH, sW)`. Default: :attr:`kernel_size`
    padding: implicit zero paddings on both sides of the input. Can be a
      single number or a tuple `(padT, padH, padW)`, Default: 0
    ceil_mode: when True, will use `ceil` instead of `floor` in the formula
        to compute the output shape
    count_include_pad: when True, will include the zero-padding in the
        averaging calculation
    divisor_override: if specified, it will be used as divisor, otherwise
        size of the pooling region will be used. Default: None
Fc              
   C   sÚ   t j ¡ s:t| ƒtur:t| fƒr:tt| f| |||||d�S |du rR|du rRtdƒ‚|du rš|dusfJ ‚t	|ƒ}t
|  d¡|d  ƒt
|  d¡|d  ƒg}|du rÆt j|  d¡|  d¡d| j| jd�}t jj | |||¡S )	ab  Applies 2D fractional max pooling over an input signal composed of several input planes.

    Fractional MaxPooling is described in detail in the paper `Fractional MaxPooling`_ by Ben Graham

    The max-pooling operation is applied in :math:`kH \times kW` regions by a stochastic
    step size determined by the target output size.
    The number of output features is equal to the number of input planes.

    Args:
        kernel_size: the size of the window to take a max over.
                     Can be a single number :math:`k` (for a square kernel of :math:`k \times k`)
                     or a tuple `(kH, kW)`
        output_size: the target output size of the image of the form :math:`oH \times oW`.
                     Can be a tuple `(oH, oW)` or a single number :math:`oH` for a square image :math:`oH \times oH`
        output_ratio: If one wants to have an output size as a ratio of the input size, this option can be given.
                      This has to be a number or tuple in the range (0, 1)
        return_indices: if ``True``, will return the indices along with the outputs.
                        Useful to pass to :func:`~torch.nn.functional.max_unpool2d`.

    Examples::
        >>> input = torch.randn(20, 16, 50, 32)
        >>> # pool of square window of size=3, and target output size 13x12
        >>> F.fractional_max_pool2d(input, 3, output_size=(13, 12))
        >>> # pool of square window and target output size being half of input image size
        >>> F.fractional_max_pool2d(input, 3, output_ratio=(0.5, 0.5))

    .. _Fractional MaxPooling:
        http://arxiv.org/abs/1412.6071
    ©Úoutput_sizeÚoutput_ratioÚreturn_indicesÚ_random_samplesNzRfractional_max_pool2d requires specifying either an output_size or an output_ratior   r   é   r   ©ÚdtypeÚdevice)ÚtorchÚjitÚis_scriptingÚtypeÚTensorr   r   Ú"fractional_max_pool2d_with_indicesÚ
ValueErrorr   ÚintÚsizeÚrandr   r   Ú_CÚ_nnÚfractional_max_pool2d©ÚinputÚkernel_sizer   r   r   r   Z_output_ratio© r.   úS/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torch/nn/functional.pyr#   c  s$    !

ýÿ$r#   c              
   C   sP   t j ¡ s:t| ƒtur:t| fƒr:tt| f| |||||d�S t| |||||ƒd S ©Nr   r   )	r   r   r    r!   r"   r   r   r*   r#   ©r,   r-   r   r   r   r   r.   r.   r/   Ú_fractional_max_pool2d˜  s    

ýþþr2   r   é   r*   )Úarg_nameZ	arg_indexÚdefaultÚif_trueÚif_falseÚmodule_nameÚ	func_namec              
   C   sî   t j ¡ s:t| ƒtur:t| fƒr:tt| f| |||||d�S |du rR|du rRtdƒ‚|du r®|dusfJ ‚t	|ƒ}t
|  d¡|d  ƒt
|  d¡|d  ƒt
|  d¡|d  ƒg}|du rÚt j|  d¡|  d¡d| j| jd	�}t jj | |||¡S )
a¢  Applies 3D fractional max pooling over an input signal composed of several input planes.

    Fractional MaxPooling is described in detail in the paper `Fractional MaxPooling`_ by Ben Graham

    The max-pooling operation is applied in :math:`kT \times kH \times kW` regions by a stochastic
    step size determined by the target output size.
    The number of output features is equal to the number of input planes.

    Args:
        kernel_size: the size of the window to take a max over.
                     Can be a single number :math:`k` (for a square kernel of :math:`k \times k \times k`)
                     or a tuple `(kT, kH, kW)`
        output_size: the target output size of the form :math:`oT \times oH \times oW`.
                     Can be a tuple `(oT, oH, oW)` or a single number :math:`oH` for a cubic output
                      :math:`oH \times oH \times oH`
        output_ratio: If one wants to have an output size as a ratio of the input size, this option can be given.
                      This has to be a number or tuple in the range (0, 1)
        return_indices: if ``True``, will return the indices along with the outputs.
                        Useful to pass to :func:`~torch.nn.functional.max_unpool3d`.

    Examples::
        >>> input = torch.randn(20, 16, 50, 32, 16)
        >>> # pool of cubic window of size=3, and target output size 13x12x11
        >>> F.fractional_max_pool3d(input, 3, output_size=(13, 12, 11))
        >>> # pool of cubic window and target output size being half of input size
        >>> F.fractional_max_pool3d(input, 3, output_ratio=(0.5, 0.5, 0.5))

    .. _Fractional MaxPooling:
        http://arxiv.org/abs/1412.6071
    r   NzRfractional_max_pool3d requires specifying either an output_size or an output_ratior   r   r   r   r3   r   )r   r   r    r!   r"   r   r   Ú"fractional_max_pool3d_with_indicesr$   r	   r%   r&   r'   r   r   r(   r)   Úfractional_max_pool3dr+   r.   r.   r/   r:   °  s&    "

ýþ$r:   c              
   C   sP   t j ¡ s:t| ƒtur:t| fƒr:tt| f| |||||d�S t| |||||ƒd S r0   )	r   r   r    r!   r"   r   r   r;   r:   r1   r.   r.   r/   Ú_fractional_max_pool3dç  s    

ýþþr<   r;   c                 C   sj   t j ¡ s<t| ƒtur<t| fƒr<tt| f| ||||||d�	S |du rVt j t	t
 g ¡}t  | |||||¡S )z‹Applies a 1D max pooling over an input signal composed of several input
    planes.

    See :class:`~torch.nn.MaxPool1d` for details.
    ©ÚstrideÚpaddingÚdilationÚ	ceil_moder   N)r   r   r    r!   r"   r   r   Úmax_pool1d_with_indicesÚannotater   r%   ©r,   r-   r>   r?   r@   rA   r   r.   r.   r/   rB   ÿ  s    

ýÿrB   c                 C   sj   t j ¡ s<t| ƒtur<t| fƒr<tt| f| ||||||d�	S |d u rVt j t	t
 g ¡}t  | |||||¡S ©Nr=   )r   r   r    r!   r"   r   r   Ú
max_pool1drC   r   r%   rD   r.   r.   r/   Ú_max_pool1d  s    

ýÿrG   é   rF   c                 C   sn   t j ¡ s<t| ƒtur<t| fƒr<tt| f| ||||||d�	S |du rVt j t	t
 g ¡}t jj | |||||¡S )z‹Applies a 2D max pooling over an input signal composed of several input
    planes.

    See :class:`~torch.nn.MaxPool2d` for details.
    r=   N)r   r   r    r!   r"   r   r   Úmax_pool2d_with_indicesrC   r   r%   r(   r)   rD   r.   r.   r/   rI   +  s    

ýrI   c                 C   sj   t j ¡ s<t| ƒtur<t| fƒr<tt| f| ||||||d�	S |d u rVt j t	t
 g ¡}t  | |||||¡S rE   )r   r   r    r!   r"   r   r   Ú
max_pool2drC   r   r%   rD   r.   r.   r/   Ú_max_pool2d>  s    

ýÿrK   rJ   c                 C   sn   t j ¡ s<t| ƒtur<t| fƒr<tt| f| ||||||d�	S |du rVt j t	t
 g ¡}t jj | |||||¡S )z‹Applies a 3D max pooling over an input signal composed of several input
    planes.

    See :class:`~torch.nn.MaxPool3d` for details.
    r=   N)r   r   r    r!   r"   r   r   Úmax_pool3d_with_indicesrC   r   r%   r(   r)   rD   r.   r.   r/   rL   V  s    

ýÿrL   c                 C   sj   t j ¡ s<t| ƒtur<t| fƒr<tt| f| ||||||d�	S |d u rVt j t	t
 g ¡}t  | |||||¡S rE   )r   r   r    r!   r"   r   r   Ú
max_pool3drC   r   r%   rD   r.   r.   r/   Ú_max_pool3dj  s    
þÿrN   rM   c                 C   s(  |   ¡ }tj tt g ¡}tt|ƒƒD ]6}| ||d  d ||  ||  d||   ¡ q&|d u rl|}n¸t|ƒt|ƒd krŒ|dd … }t|ƒt|ƒkr¾t	d 
t|ƒt|ƒd t|ƒ¡ƒ‚tt|ƒƒD ]T}|| ||  }	|| ||  }
|	||   k �r|
k sÊn t	d 
|||	|
¡ƒ‚qÊ|}|S )Nr   r   zZoutput_size should be a sequence containing {} or {} elements, but it has a length of '{}'z;invalid output_size "{}" (dim {} must be between {} and {}))r&   r   r   rC   r   r%   ÚrangeÚlenÚappendr$   Úformat)r,   r-   r>   r?   r   Z
input_sizeZdefault_sizeÚdÚretZmin_sizeÚmax_sizer.   r.   r/   Ú_unpool_output_size�  s8    ÿ
ÿýÿÿrV   c              
   C   s²   t j ¡ s:t| ƒtur:t| fƒr:tt| f| |||||d�S t|ƒ}|durTt|ƒ}n|}t|ƒ}t	| ||||ƒ}t
|tƒr†|dg }n|d }t jj |  d¡| d¡|¡ d¡S )zkComputes a partial inverse of :class:`MaxPool1d`.

    See :class:`~torch.nn.MaxUnpool1d` for details.
    ©r>   r?   r   Nr   )r   r   )r   r   r    r!   r"   r   r   Úmax_unpool1dr   rV   Ú
isinstanceÚlistr(   r)   Úmax_unpool2dÚ	unsqueezeÚsqueeze©r,   Úindicesr-   r>   r?   r   Z_strider.   r.   r/   rX   ž  s,    
þ

ÿ
ÿÿrX   c              
   C   s‚   t j ¡ s:t| ƒtur:t| fƒr:tt| f| |||||d�S t|ƒ}|durTt|ƒ}n|}t|ƒ}t	| ||||ƒ}t j
j | ||¡S )zkComputes a partial inverse of :class:`MaxPool2d`.

    See :class:`~torch.nn.MaxUnpool2d` for details.
    rW   N)r   r   r    r!   r"   r   r   r[   r   rV   r(   r)   r^   r.   r.   r/   r[   º  s    
þ

ÿr[   c              
   C   s†   t j ¡ s:t| ƒtur:t| fƒr:tt| f| |||||d�S t|ƒ}|durTt|ƒ}n|}t|ƒ}t	| ||||ƒ}t j
j | ||||¡S )zkComputes a partial inverse of :class:`MaxPool3d`.

    See :class:`~torch.nn.MaxUnpool3d` for details.
    rW   N)r   r   r    r!   r"   r   r   Úmax_unpool3dr	   rV   r(   r)   r^   r.   r.   r/   r`   Ñ  s"    
þ

ÿ
ÿr`   c              	   C   s¨   t j ¡ s8t| ƒtur8t| fƒr8tt| f| ||||d�S t 	|¡\}}|durft
|  |¡||d|ƒ}nt
|  |¡|d|d�}t  |¡tt  |¡ƒ  || ¡ d| ¡S )zóApplies a 2D power-average pooling over an input signal composed of
    several input planes. If the sum of all inputs to the power of `p` is
    zero, the gradient is set to zero as well.

    See :class:`~torch.nn.LPPool2d` for details.
    ©r>   rA   Nr   ©r?   rA   ç      ð?)r   r   r    r!   r"   r   r   Ú	lp_pool2dr   r   Ú
avg_pool2dÚpowÚsignÚreluÚabsÚmul)r,   Ú	norm_typer-   r>   rA   ÚkwZkhÚoutr.   r.   r/   rd   é  s    
þrd   c              	   C   s–   t j ¡ s8t| ƒtur8t| fƒr8tt| f| ||||d�S |durXt|  	|¡||d|ƒ}nt|  	|¡|d|d�}t  
|¡tt  |¡ƒ  |¡ 	d| ¡S )zóApplies a 1D power-average pooling over an input signal composed of
    several input planes. If the sum of all inputs to the power of `p` is
    zero, the gradient is set to zero as well.

    See :class:`~torch.nn.LPPool1d` for details.
    ra   Nr   rb   rc   )r   r   r    r!   r"   r   r   Ú	lp_pool1dÚ
avg_pool1drf   rg   rh   ri   rj   )r,   rk   r-   r>   rA   rm   r.   r.   r/   rn   ÿ  s    
þrn   c                 C   s@   t j ¡ s4t| ƒtur4t| fƒr4tt| f| ||d�S t  | |¡S )aC  Applies a 1D adaptive max pooling over an input signal composed of
    several input planes.

    See :class:`~torch.nn.AdaptiveMaxPool1d` for details and output shape.

    Args:
        output_size: the target output size (single integer)
        return_indices: whether to return pooling indices. Default: ``False``
    ©r   )	r   r   r    r!   r"   r   r   Ú adaptive_max_pool1d_with_indicesÚadaptive_max_pool1d©r,   r   r   r.   r.   r/   rq     s    

þrq   c                 C   sB   t j ¡ s4t| ƒtur4t| fƒr4tt| f| ||d�S t| |ƒd S ©Nrp   r   )	r   r   r    r!   r"   r   r   rr   rq   rs   r.   r.   r/   Ú_adaptive_max_pool1d'  s    

þru   rr   c                 C   sR   t j ¡ s4t| ƒtur4t| fƒr4tt| f| ||d�S t||  	¡ ƒ}t j
j | |¡S )ag  Applies a 2D adaptive max pooling over an input signal composed of
    several input planes.

    See :class:`~torch.nn.AdaptiveMaxPool2d` for details and output shape.

    Args:
        output_size: the target output size (single integer or
            double-integer tuple)
        return_indices: whether to return pooling indices. Default: ``False``
    rp   )r   r   r    r!   r"   r   r   Ú adaptive_max_pool2d_with_indicesr
   r&   r(   r)   Úadaptive_max_pool2drs   r.   r.   r/   rv   :  s    

þrv   c                 C   sB   t j ¡ s4t| ƒtur4t| fƒr4tt| f| ||d�S t| |ƒd S rt   )	r   r   r    r!   r"   r   r   rw   rv   rs   r.   r.   r/   Ú_adaptive_max_pool2dO  s    

þrx   rw   c                 C   sR   t j ¡ s4t| ƒtur4t| fƒr4tt| f| ||d�S t||  	¡ ƒ}t j
j | |¡S )ag  Applies a 3D adaptive max pooling over an input signal composed of
    several input planes.

    See :class:`~torch.nn.AdaptiveMaxPool3d` for details and output shape.

    Args:
        output_size: the target output size (single integer or
            triple-integer tuple)
        return_indices: whether to return pooling indices. Default: ``False``
    rp   )r   r   r    r!   r"   r   r   Ú adaptive_max_pool3d_with_indicesr
   r&   r(   r)   Úadaptive_max_pool3drs   r.   r.   r/   ry   b  s    

þry   c                 C   sB   t j ¡ s4t| ƒtur4t| fƒr4tt| f| ||d�S t| |ƒd S rt   )	r   r   r    r!   r"   r   r   rz   ry   rs   r.   r.   r/   Ú_adaptive_max_pool3dw  s    

þr{   rz   a  
adaptive_avg_pool1d(input, output_size) -> Tensor

Applies a 1D adaptive average pooling over an input signal composed of
several input planes.

See :class:`~torch.nn.AdaptiveAvgPool1d` for details and output shape.

Args:
    output_size: the target output size (single integer)
c                 C   sN   t j ¡ s0t| ƒtur0t| fƒr0tt| f| |ƒS t||  	¡ ƒ}t j
j | |¡S )a"  
    Applies a 2D adaptive average pooling over an input signal composed of
    several input planes.

    See :class:`~torch.nn.AdaptiveAvgPool2d` for details and output shape.

    Args:
        output_size: the target output size (single integer or
            double-integer tuple)
    )r   r   r    r!   r"   r   r   Úadaptive_avg_pool2dr
   r&   r(   r)   ©r,   r   Z_output_sizer.   r.   r/   r|   —  s    

ÿr|   c                 C   sN   t j ¡ s0t| ƒtur0t| fƒr0tt| f| |ƒS t||  	¡ ƒ}t j
j | |¡S )a"  
    Applies a 3D adaptive average pooling over an input signal composed of
    several input planes.

    See :class:`~torch.nn.AdaptiveAvgPool3d` for details and output shape.

    Args:
        output_size: the target output size (single integer or
            triple-integer tuple)
    )r   r   r    r!   r"   r   r   Úadaptive_avg_pool3dr
   r&   r(   r)   r}   r.   r.   r/   r~   «  s    

ÿr~   ç      à?Tc                 C   st   t j ¡ s6t| ƒtur6t| fƒr6tt| f| |||d�S |dk sF|dkrTtd 	|¡ƒ‚|rft
 | ||¡S t
 | ||¡S )aº  
    During training, randomly zeroes some of the elements of the input
    tensor with probability :attr:`p` using samples from a Bernoulli
    distribution.

    See :class:`~torch.nn.Dropout` for details.

    Args:
        p: probability of an element to be zeroed. Default: 0.5
        training: apply dropout if is ``True``. Default: ``True``
        inplace: If set to ``True``, will do this operation in-place. Default: ``False``
    ©ÚpÚtrainingÚinplaceç        rc   ú9dropout probability has to be between 0 and 1, but got {})r   r   r    r!   r"   r   r   Údropoutr$   rR   r   Zdropout_©r,   r�   r‚   rƒ   r.   r.   r/   r†   À  s    
ÿÿÿþr†   c                 C   st   t j ¡ s6t| ƒtur6t| fƒr6tt| f| |||d�S |dk sF|dkrTtd 	|¡ƒ‚|rft
 | ||¡S t
 | ||¡S )z^Applies alpha dropout to the input.

    See :class:`~torch.nn.AlphaDropout` for details.
    r€   r„   rc   r…   )r   r   r    r!   r"   r   r   Úalpha_dropoutr$   rR   r   Zalpha_dropout_r‡   r.   r.   r/   rˆ   Ú  s    
ÿÿÿþrˆ   c                 C   st   t j ¡ s6t| ƒtur6t| fƒr6tt| f| |||d�S |dk sF|dkrTtd 	|¡ƒ‚|rft
 | ||¡S t
 | ||¡S )a�  
    Randomly zero out entire channels (a channel is a 2D feature map,
    e.g., the :math:`j`-th channel of the :math:`i`-th sample in the
    batched input is a 2D tensor :math:`\text{input}[i, j]`) of the input tensor).
    Each channel will be zeroed out independently on every forward call with
    probability :attr:`p` using samples from a Bernoulli distribution.

    See :class:`~torch.nn.Dropout2d` for details.

    Args:
        p: probability of a channel to be zeroed. Default: 0.5
        training: apply dropout if is ``True``. Default: ``True``
        inplace: If set to ``True``, will do this operation in-place. Default: ``False``
    r€   r„   rc   r…   )r   r   r    r!   r"   r   r   Ú	dropout2dr$   rR   r   Úfeature_dropout_Úfeature_dropoutr‡   r.   r.   r/   r‰   ì  s    
ÿÿÿþr‰   c                 C   st   t j ¡ s6t| ƒtur6t| fƒr6tt| f| |||d�S |dk sF|dkrTtd 	|¡ƒ‚|rft
 | ||¡S t
 | ||¡S )a�  
    Randomly zero out entire channels (a channel is a 3D feature map,
    e.g., the :math:`j`-th channel of the :math:`i`-th sample in the
    batched input is a 3D tensor :math:`\text{input}[i, j]`) of the input tensor).
    Each channel will be zeroed out independently on every forward call with
    probability :attr:`p` using samples from a Bernoulli distribution.

    See :class:`~torch.nn.Dropout3d` for details.

    Args:
        p: probability of a channel to be zeroed. Default: 0.5
        training: apply dropout if is ``True``. Default: ``True``
        inplace: If set to ``True``, will do this operation in-place. Default: ``False``
    r€   r„   rc   r…   )r   r   r    r!   r"   r   r   Ú	dropout3dr$   rR   r   rŠ   r‹   r‡   r.   r.   r/   rŒ     s    
ÿÿÿþrŒ   c                 C   st   t j ¡ s6t| ƒtur6t| fƒr6tt| f| |||d�S |dk sF|dkrTtd 	|¡ƒ‚|rft
 | ||¡S t
 | ||¡S )a¿  
    Randomly masks out entire channels (a channel is a feature map,
    e.g. the :math:`j`-th channel of the :math:`i`-th sample in the batch input
    is a tensor :math:`\text{input}[i, j]`) of the input tensor). Instead of
    setting activations to zero, as in regular Dropout, the activations are set
    to the negative saturation value of the SELU activation function.

    Each element will be masked independently on every forward call with
    probability :attr:`p` using samples from a Bernoulli distribution.
    The elements to be masked are randomized on every forward call, and scaled
    and shifted to maintain zero mean and unit variance.

    See :class:`~torch.nn.FeatureAlphaDropout` for details.

    Args:
        p: dropout probability of a channel to be zeroed. Default: 0.5
        training: apply dropout if is ``True``. Default: ``True``
        inplace: If set to ``True``, will do this operation in-place. Default: ``False``
    r€   r„   rc   r…   )r   r   r    r!   r"   r   r   Úfeature_alpha_dropoutr$   rR   r   Zfeature_alpha_dropout_r‡   r.   r.   r/   r�   &  s    
þÿÿþr�   c                 C   s\   t j ¡ s6t| ƒtur6t| fƒr6tt| f| |||d�S |rJt 	| ||¡}nt 
| ||¡}|S )ziThresholds each element of the input Tensor.

    See :class:`~torch.nn.Threshold` for more details.
    ©rƒ   )r   r   r    r!   r"   r   r   Ú
_thresholdr   Ú
threshold_Ú	threshold)r,   r‘   Úvaluerƒ   Úresultr.   r.   r/   r�   H  s    
ÿr�   zX
threshold_(input, threshold, value) -> Tensor

In-place version of :func:`~threshold`.
)r,   rƒ   Úreturnc                 C   sP   t j ¡ s2t| ƒtur2t| fƒr2tt| f| |d�S |rBt  | ¡}n
t  | ¡}|S )z™relu(input, inplace=False) -> Tensor

    Applies the rectified linear unit function element-wise. See
    :class:`~torch.nn.ReLU` for more details.
    rŽ   )	r   r   r    r!   r"   r   r   rh   Úrelu_©r,   rƒ   r“   r.   r.   r/   rh   d  s    

rh   z<
relu_(input) -> Tensor

In-place version of :func:`~relu`.
éÿÿÿÿ)r,   Údimr”   c                 C   sV   t j ¡ s2t| ƒtur2t| fƒr2tt| f| |d�S |  ¡ dkrFt	dƒ‚t j
j | |¡S )a  
    glu(input, dim=-1) -> Tensor

    The gated linear unit. Computes:

    .. math ::
        \text{GLU}(a, b) = a \otimes \sigma(b)

    where `input` is split in half along `dim` to form `a` and `b`, :math:`\sigma`
    is the sigmoid function and :math:`\otimes` is the element-wise product between matrices.

    See `Language Modeling with Gated Convolutional Networks <https://arxiv.org/abs/1612.08083>`_.

    Args:
        input (Tensor): input tensor
        dim (int): dimension on which to split the input. Default: -1
    ©r˜   r   z>glu does not support scalars because halving size must be even)r   r   r    r!   r"   r   r   Úglur˜   ÚRuntimeErrorr(   r)   )r,   r˜   r.   r.   r/   rš   {  s    
rš   ç      ð¿rc   )r,   Úmin_valÚmax_valrƒ   r”   c                 C   sd   t j ¡ s6t| ƒtur6t| fƒr6tt| f| |||d�S |rNt jj	 
| ||¡}nt jj	 | ||¡}|S )z²
    hardtanh(input, min_val=-1., max_val=1., inplace=False) -> Tensor

    Applies the HardTanh function element-wise. See :class:`~torch.nn.Hardtanh` for more
    details.
    )r�   rž   rƒ   )r   r   r    r!   r"   r   r   Úhardtanhr(   r)   Ú	hardtanh_)r,   r�   rž   rƒ   r“   r.   r.   r/   rŸ   •  s    
þrŸ   z]
hardtanh_(input, min_val=-1., max_val=1.) -> Tensor

In-place version of :func:`~hardtanh`.
c                 C   s@   t j ¡ s2t| ƒtur2t| fƒr2tt| f| |d�S t| dd|ƒS )z³relu6(input, inplace=False) -> Tensor

    Applies the element-wise function :math:`\text{ReLU6}(x) = \min(\max(0,x), 6)`.

    See :class:`~torch.nn.ReLU6` for more details.
    rŽ   r„   g      @)	r   r   r    r!   r"   r   r   Úrelu6rŸ   ©r,   rƒ   r.   r.   r/   r¡   ¯  s    
r¡   c                 C   s^   t j ¡ s4t| ƒtur4t| fƒr4tt| f| ||d�S |rJt jj	 
| |¡}nt jj	 | |¡}|S )z•Applies element-wise,
    :math:`\text{ELU}(x) = \max(0,x) + \min(0, \alpha * (\exp(x) - 1))`.

    See :class:`~torch.nn.ELU` for more details.
    ©Úalpharƒ   )r   r   r    r!   r"   r   r   Úelur(   r)   Úelu_©r,   r¤   rƒ   r“   r.   r.   r/   r¥   ½  s    
ÿr¥   zD
elu_(input, alpha=1.) -> Tensor

In-place version of :func:`~elu`.
c                 C   sP   t j ¡ s2t| ƒtur2t| fƒr2tt| f| |d�S |rBt  | ¡}n
t  | ¡}|S )a>  selu(input, inplace=False) -> Tensor

    Applies element-wise,
    :math:`\text{SELU}(x) = scale * (\max(0,x) + \min(0, \alpha * (\exp(x) - 1)))`,
    with :math:`\alpha=1.6732632423543772848170429916717` and
    :math:`scale=1.0507009873554804934193349852946`.

    See :class:`~torch.nn.SELU` for more details.
    rŽ   )	r   r   r    r!   r"   r   r   ÚseluÚselu_r–   r.   r.   r/   r¨   Ö  s    

r¨   z<
selu_(input) -> Tensor

In-place version of :func:`~selu`.
c                 C   sV   t j ¡ s4t| ƒtur4t| fƒr4tt| f| ||d�S |rFt  | |¡}nt  | |¡}|S )zÒcelu(input, alpha=1., inplace=False) -> Tensor

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

    See :class:`~torch.nn.CELU` for more details.
    r£   )	r   r   r    r!   r"   r   r   ÚceluÚcelu_r§   r.   r.   r/   rª   ò  s    	
ÿrª   zF
celu_(input, alpha=1.) -> Tensor

In-place version of :func:`~celu`.
ç{®Gáz„?)r,   Únegative_sloperƒ   r”   c                 C   s^   t j ¡ s4t| ƒtur4t| fƒr4tt| f| ||d�S |rJt jj	 
| |¡}nt jj	 | |¡}|S )zï
    leaky_relu(input, negative_slope=0.01, inplace=False) -> Tensor

    Applies element-wise,
    :math:`\text{LeakyReLU}(x) = \max(0, x) + \text{negative\_slope} * \min(0, x)`

    See :class:`~torch.nn.LeakyReLU` for more details.
    )r­   rƒ   )r   r   r    r!   r"   r   r   Ú
leaky_relur(   r)   Úleaky_relu_)r,   r­   rƒ   r“   r.   r.   r/   r®     s    	

þr®   z]
leaky_relu_(input, negative_slope=0.01) -> Tensor

In-place version of :func:`~leaky_relu`.
c                 C   s<   t j ¡ s0t| ƒtur0t| fƒr0tt| f| |ƒS t  | |¡S )zíprelu(input, weight) -> Tensor

    Applies element-wise the function
    :math:`\text{PReLU}(x) = \max(0,x) + \text{weight} * \min(0,x)` where weight is a
    learnable parameter.

    See :class:`~torch.nn.PReLU` for more details.
    )r   r   r    r!   r"   r   r   Úprelu)r,   Úweightr.   r.   r/   r°   (  s    

r°   ç      À?çUUUUUUÕ?c              	   C   sb   t j ¡ s8t| ƒtur8t| fƒr8tt| f| ||||d�S |rNt  | |||¡}nt  | |||¡}|S )z¢rrelu(input, lower=1./8, upper=1./3, training=False, inplace=False) -> Tensor

    Randomized leaky ReLU.

    See :class:`~torch.nn.RReLU` for more details.
    )ÚlowerÚupperr‚   rƒ   )	r   r   r    r!   r"   r   r   ÚrreluÚrrelu_)r,   r´   rµ   r‚   rƒ   r“   r.   r.   r/   r¶   8  s    
þr¶   zf
rrelu_(input, lower=1./8, upper=1./3, training=False) -> Tensor

In-place version of :func:`~rrelu`.
z´
logsigmoid(input) -> Tensor

Applies element-wise :math:`\text{LogSigmoid}(x_i) = \log \left(\frac{1}{1 + \exp(-x_i)}\right)`

See :class:`~torch.nn.LogSigmoid` for more details.
c                 C   s<   t j ¡ s.t| ƒtur.t| fƒr.tt| f| ƒS t jj	 | ¡S )a  gelu(input) -> Tensor

    Applies element-wise the function
    :math:`\text{GELU}(x) = x * \Phi(x)`

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

    See `Gaussian Error Linear Units (GELUs) <https://arxiv.org/abs/1606.08415>`_.
    )
r   r   r    r!   r"   r   r   Úgelur(   r)   ©r,   r.   r.   r/   r¸   Z  s    

r¸   c                 C   s>   t j ¡ s2t| ƒtur2t| fƒr2tt| f| |d�S t  | |¡S )zŸ
    hardshrink(input, lambd=0.5) -> Tensor

    Applies the hard shrinkage function element-wise

    See :class:`~torch.nn.Hardshrink` for more details.
    )Úlambd)r   r   r    r!   r"   r   r   Ú
hardshrink)r,   rº   r.   r.   r/   r»   j  s    	
r»   c                 C   s:   t j ¡ s.t| ƒtur.t| fƒr.tt| f| ƒS | |  ¡  S )z¦tanhshrink(input) -> Tensor

    Applies element-wise, :math:`\text{Tanhshrink}(x) = x - \text{Tanh}(x)`

    See :class:`~torch.nn.Tanhshrink` for more details.
    )	r   r   r    r!   r"   r   r   Ú
tanhshrinkÚtanhr¹   r.   r.   r/   r¼   y  s    
r¼   c                 C   s>   t j ¡ s.t| ƒtur.t| fƒr.tt| f| ƒS | |  ¡ d  S )z¬softsign(input) -> Tensor

    Applies element-wise, the function :math:`\text{SoftSign}(x) = \frac{x}{1 + |x|}`

    See :class:`~torch.nn.Softsign` for more details.
    r   )	r   r   r    r!   r"   r   r   Úsoftsignri   r¹   r.   r.   r/   r¾   †  s    
r¾   aJ  
softplus(input, beta=1, threshold=20) -> Tensor

Applies element-wise, the function :math:`\text{Softplus}(x) = \frac{1}{\beta} * \log(1 + \exp(\beta * x))`.

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

See :class:`~torch.nn.Softplus` for more details.
c                 C   s:   t jd | ¡|d� |dks,|dks,|dkr2d}nd}|S )NzfImplicit dimension choice for {} has been deprecated. Change the call to include dim=X as an argument.©Ú
stacklevelr   r   r   )ÚwarningsÚwarnrR   )ÚnameÚndimrÀ   rT   r.   r.   r/   Ú_get_softmax_dimŸ  s    ÿÿrÅ   r   c                 C   sx   t j ¡ s6t| ƒtur6t| fƒr6tt| f| |||d�S |du rNtd|  	¡ |ƒ}|du rd|   
|¡}n|  j
||d�}|S )a{  Applies a softmin function.

    Note that :math:`\text{Softmin}(x) = \text{Softmax}(-x)`. See softmax definition for mathematical formula.

    See :class:`~torch.nn.Softmin` for more details.

    Arguments:
        input (Tensor): input
        dim (int): A dimension along which softmin will be computed (so every slice
            along dim will sum to 1).
        dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.
          If specified, the input tensor is casted to :attr:`dtype` before the operation
          is performed. This is useful for preventing data type overflows. Default: None.
    ©r˜   Ú_stacklevelr   NÚsoftmin©r   )r   r   r    r!   r"   r   r   rÈ   rÅ   r˜   Úsoftmax©r,   r˜   rÇ   r   rT   r.   r.   r/   rÈ   ª  s    
ÿrÈ   c                 C   st   t j ¡ s6t| ƒtur6t| fƒr6tt| f| |||d�S |du rNtd|  	¡ |ƒ}|du rb|  |¡}n| j||d�}|S )a¨  Applies a softmax function.

    Softmax is defined as:

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

    It is applied to all slices along dim, and will re-scale them so that the elements
    lie in the range `[0, 1]` and sum to 1.

    See :class:`~torch.nn.Softmax` for more details.

    Arguments:
        input (Tensor): input
        dim (int): A dimension along which softmax will be computed.
        dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.
          If specified, the input tensor is casted to :attr:`dtype` before the operation
          is performed. This is useful for preventing data type overflows. Default: None.

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

    rÆ   NrÊ   rÉ   )
r   r   r    r!   r"   r   r   rÊ   rÅ   r˜   rË   r.   r.   r/   rÊ   Ç  s    
ÿrÊ   ç»½×Ùß|Û=c           
   	   C   sÄ   t j ¡ s8t| ƒtur8t| fƒr8tt| f| ||||d�S |dkrJt 	d¡ t j
| t jd� ¡  ¡  }| | | }| |¡}|r¼|j|dd�d }t j| t jd� ||d¡}|| ¡  | }	n|}	|	S )	a  
    Samples from the Gumbel-Softmax distribution (`Link 1`_  `Link 2`_) and optionally discretizes.

    Args:
      logits: `[..., num_features]` unnormalized log probabilities
      tau: non-negative scalar temperature
      hard: if ``True``, the returned samples will be discretized as one-hot vectors,
            but will be differentiated as if it is the soft sample in autograd
      dim (int): A dimension along which softmax will be computed. Default: -1.

    Returns:
      Sampled tensor of same shape as `logits` from the Gumbel-Softmax distribution.
      If ``hard=True``, the returned samples will be one-hot, otherwise they will
      be probability distributions that sum to 1 across `dim`.

    .. note::
      This function is here for legacy reasons, may be removed from nn.Functional in the future.

    .. note::
      The main trick for `hard` is to do  `y_hard - y_soft.detach() + y_soft`

      It achieves two things:
      - makes the output value exactly one-hot
      (since we add then subtract y_soft value)
      - makes the gradient equal to y_soft gradient
      (since we strip all other gradients)

    Examples::
        >>> logits = torch.randn(20, 32)
        >>> # Sample soft categorical using reparametrization trick:
        >>> F.gumbel_softmax(logits, tau=1, hard=False)
        >>> # Sample hard categorical using "Straight-through" trick:
        >>> F.gumbel_softmax(logits, tau=1, hard=True)

    .. _Link 1:
        https://arxiv.org/abs/1611.00712
    .. _Link 2:
        https://arxiv.org/abs/1611.01144
    )ÚtauÚhardÚepsr˜   rÌ   z0`eps` parameter is deprecated and has no effect.)Zmemory_formatT©Úkeepdimr   rc   )r   r   r    r!   r"   r   r   Úgumbel_softmaxrÁ   rÂ   Z
empty_likeZlegacy_contiguous_formatZexponential_ÚlogrÊ   ÚmaxZ
zeros_likeZscatter_Údetach)
ZlogitsrÍ   rÎ   rÏ   r˜   ZgumbelsZy_softÚindexZy_hardrT   r.   r.   r/   rÒ   î  s     )
ÿ

rÒ   c                 C   st   t j ¡ s6t| ƒtur6t| fƒr6tt| f| |||d�S |du rNtd|  	¡ |ƒ}|du rb|  |¡}n| j||d�}|S )aÔ  Applies a softmax followed by a logarithm.

    While mathematically equivalent to log(softmax(x)), doing these two
    operations separately is slower, and numerically unstable. This function
    uses an alternative formulation to compute the output and gradient correctly.

    See :class:`~torch.nn.LogSoftmax` for more details.

    Arguments:
        input (Tensor): input
        dim (int): A dimension along which log_softmax will be computed.
        dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.
          If specified, the input tensor is casted to :attr:`dtype` before the operation
          is performed. This is useful for preventing data type overflows. Default: None.
    rÆ   NÚlog_softmaxrÉ   )
r   r   r    r!   r"   r   r   r×   rÅ   r˜   rË   r.   r.   r/   r×   -  s    
ÿr×   zŽ
softshrink(input, lambd=0.5) -> Tensor

Applies the soft shrinkage function elementwise

See :class:`~torch.nn.Softshrink` for more details.
c                 C   s   t  d¡ |  ¡ S )z¾tanh(input) -> Tensor

    Applies element-wise,
    :math:`\text{Tanh}(x) = \tanh(x) = \frac{\exp(x) - \exp(-x)}{\exp(x) + \exp(-x)}`

    See :class:`~torch.nn.Tanh` for more details.
    z9nn.functional.tanh is deprecated. Use torch.tanh instead.)rÁ   rÂ   r½   r¹   r.   r.   r/   r½   T  s    
r½   c                 C   s   t  d¡ |  ¡ S )z­sigmoid(input) -> Tensor

    Applies the element-wise function :math:`\text{Sigmoid}(x) = \frac{1}{1 + \exp(-x)}`

    See :class:`~torch.nn.Sigmoid` for more details.
    z?nn.functional.sigmoid is deprecated. Use torch.sigmoid instead.)rÁ   rÂ   Úsigmoidr¹   r.   r.   r/   rØ   `  s    
rØ   c                 C   sR   t j ¡ s2t| ƒtur2t| fƒr2tt| f| |d�S |rDt jj	 
| ¡S t jj	 | ¡S )a´  hardsigmoid(input) -> Tensor

    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: If set to ``True``, will do this operation in-place. Default: ``False``

    See :class:`~torch.nn.Hardsigmoid` for more details.
    rŽ   )r   r   r    r!   r"   r   r   Úhardsigmoidr(   r)   Zhardsigmoid_r¢   r.   r.   r/   rÙ   k  s    
rÙ   c                 C   sŒ   | |f}t j ¡ s>tdd„ |D ƒƒr>t|ƒr>tt|| ||d�S |  ¡ dkrf|durft  || | 	¡ ¡}n"|  
| 	¡ ¡}|dur„||7 }|}|S )a¯  
    Applies a linear transformation to the incoming data: :math:`y = xA^T + b`.

    This operator supports :ref:`TensorFloat32<tf32_on_ampere>`.

    Shape:

        - Input: :math:`(N, *, in\_features)` N is the batch size, `*` means any number of
          additional dimensions
        - Weight: :math:`(out\_features, in\_features)`
        - Bias: :math:`(out\_features)`
        - Output: :math:`(N, *, out\_features)`
    c                 S   s   g | ]}t |ƒtu‘qS r.   ©r!   r"   ©Ú.0Útr.   r.   r/   Ú
<listcomp>–  ó    zlinear.<locals>.<listcomp>)Úbiasr   N)r   r   r    Úanyr   r   Úlinearr˜   ZaddmmrÝ   Úmatmul)r,   r±   rà   Útens_opsrT   Úoutputr.   r.   r/   râ   …  s    
râ   c                 C   s   t  | |||¡S )a×  
    Applies a bilinear transformation to the incoming data:
    :math:`y = x_1^T A x_2 + b`

    Shape:

        - input1: :math:`(N, *, H_{in1})` where :math:`H_{in1}=\text{in1\_features}`
          and :math:`*` means any number of additional dimensions.
          All but the last dimension of the inputs should be the same.
        - input2: :math:`(N, *, H_{in2})` where :math:`H_{in2}=\text{in2\_features}`
        - weight: :math:`(\text{out\_features}, \text{in1\_features},
          \text{in2\_features})`
        - bias: :math:`(\text{out\_features})`
        - output: :math:`(N, *, H_{out})` where :math:`H_{out}=\text{out\_features}`
          and all but the last dimension are the same shape as the input.
    )r   Úbilinear)Úinput1Úinput2r±   rà   r.   r.   r/   ræ   £  s    ræ   c                 C   sR   t j ¡ s2t| ƒtur2t| fƒr2tt| f| |d�S |rDt jj	 
| ¡S t jj	 | ¡S )a©  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.

    See :class:`~torch.nn.SiLU` for more details.
    rŽ   )r   r   r    r!   r"   r   r   Úsilur(   r)   Zsilu_r¢   r.   r.   r/   ré   ·  s    
ré   c                 C   sR   t j ¡ s2t| ƒtur2t| fƒr2tt| f| |d�S |rDt jj	 
| ¡S t jj	 | ¡S )aÈ  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}

    See :class:`~torch.nn.Hardswish` for more details.

    .. _`Searching for MobileNetV3`:
        https://arxiv.org/abs/1905.02244
    rŽ   )r   r   r    r!   r"   r   r   Ú	hardswishr(   r)   Z
hardswish_r¢   r.   r.   r/   rê   Ï  s    
rê   c                 C   s<   t  ¡ �  t  | |||¡ W d   ƒ n1 s.0    Y  d S ©N)r   Zno_gradZembedding_renorm_)r±   r,   Úmax_normrk   r.   r.   r/   Ú_no_grad_embedding_renorm_è  s    
rí   ç       @c                 C   sŒ   |durX|dkr(||  d¡k sVJ dƒ‚q\|dk r\||  d¡ ksHJ dƒ‚|  d¡| }nd}|durz|  ¡ } t|| ||ƒ t || |||¡S )a  A simple lookup table that looks up embeddings in a fixed dictionary and size.

    This module is often used to retrieve word embeddings using indices.
    The input to the module is a list of indices, and the embedding matrix,
    and the output is the corresponding word embeddings.

    See :class:`torch.nn.Embedding` for more details.

    Args:
        input (LongTensor): Tensor containing indices into the embedding matrix
        weight (Tensor): The embedding matrix with number of rows equal to the maximum possible index + 1,
            and number of columns equal to the embedding size
        padding_idx (int, optional): If given, pads the output with the embedding vector at :attr:`padding_idx`
                                         (initialized to zeros) whenever it encounters the index.
        max_norm (float, optional): If given, each embedding vector with norm larger than :attr:`max_norm`
                                    is renormalized to have norm :attr:`max_norm`.
                                    Note: this will modify :attr:`weight` in-place.
        norm_type (float, optional): The p of the p-norm to compute for the :attr:`max_norm` option. Default ``2``.
        scale_grad_by_freq (boolean, optional): If given, this will scale gradients by the inverse of frequency of
                                                the words in the mini-batch. Default ``False``.
        sparse (bool, optional): If ``True``, gradient w.r.t. :attr:`weight` will be a sparse tensor. See Notes under
                                 :class:`torch.nn.Embedding` for more details regarding sparse gradients.

    Shape:
        - Input: LongTensor of arbitrary shape containing the indices to extract
        - Weight: Embedding matrix of floating point type with shape `(V, embedding_dim)`,
                            where V = maximum index + 1 and embedding_dim = the embedding size
        - Output: `(*, embedding_dim)`, where `*` is the input shape

    Examples::

        >>> # a batch of 2 samples of 4 indices each
        >>> input = torch.tensor([[1,2,4,5],[4,3,2,9]])
        >>> # an embedding matrix containing 10 tensors of size 3
        >>> embedding_matrix = torch.rand(10, 3)
        >>> F.embedding(input, embedding_matrix)
        tensor([[[ 0.8490,  0.9625,  0.6753],
                 [ 0.9666,  0.7761,  0.6108],
                 [ 0.6246,  0.9751,  0.3618],
                 [ 0.4161,  0.2419,  0.7383]],

                [[ 0.6246,  0.9751,  0.3618],
                 [ 0.0237,  0.7794,  0.0528],
                 [ 0.9666,  0.7761,  0.6108],
                 [ 0.3385,  0.8612,  0.1867]]])

        >>> # example with padding_idx
        >>> weights = torch.rand(10, 3)
        >>> weights[0, :].zero_()
        >>> embedding_matrix = weights
        >>> input = torch.tensor([[0,2,0,5]])
        >>> F.embedding(input, embedding_matrix, padding_idx=0)
        tensor([[[ 0.0000,  0.0000,  0.0000],
                 [ 0.5609,  0.5384,  0.8720],
                 [ 0.0000,  0.0000,  0.0000],
                 [ 0.6262,  0.2438,  0.7471]]])
    Nr   z)Padding_idx must be within num_embeddingsr—   )r&   Ú
contiguousrí   r   Ú	embedding)r,   r±   Zpadding_idxrì   rk   Úscale_grad_by_freqÚsparser.   r.   r/   rð   î  s    <rð   Úmeanc
                 C   s  t j ¡ sL| |f}
tdd„ |
D ƒƒrLt|
ƒrLtt|
| |||||||||	d�S |jt jkrt|  	¡ rtt
 d¡ | | }} |dur |  ¡ | ¡ kr td |j| j¡ƒ‚|  ¡ dk�r |durÞd}t j ¡ sÐtt|ƒƒ}td	 |¡ƒ‚t jd
|  ¡ |  d¡t j| jd�}|  d¡} |du�rj| d¡}nJ|  ¡ dk�rX|du �r@tdƒ‚| ¡ dk�rjtdƒ‚ntd |  ¡ ¡ƒ‚|dk�rzd
}nD|dk�rŠd}n4|dk�r¶d}|�r¦tdƒ‚|�r¾tdƒ‚ntdƒ‚|du�rÖt|| ||ƒ |du�rø|dk�røtd |¡ƒ‚t  || ||||||	¡\}}}}|S )aÎ  Computes sums, means or maxes of `bags` of embeddings, without instantiating the
    intermediate embeddings.

    See :class:`torch.nn.EmbeddingBag` for more details.

    Note:
        When using the CUDA backend, this operation may induce nondeterministic
        behaviour in its backward pass that is not easily switched off.
        Please see the notes on :doc:`/notes/randomness` for background.

    Args:
        input (LongTensor): Tensor containing bags of indices into the embedding matrix
        weight (Tensor): The embedding matrix with number of rows equal to the maximum possible index + 1,
            and number of columns equal to the embedding size
        offsets (LongTensor, optional): Only used when :attr:`input` is 1D. :attr:`offsets` determines
                             the starting index position of each bag (sequence) in :attr:`input`.
        max_norm (float, optional): If given, each embedding vector with norm larger than :attr:`max_norm`
                                    is renormalized to have norm :attr:`max_norm`.
                                    Note: this will modify :attr:`weight` in-place.
        norm_type (float, optional): The ``p`` in the ``p``-norm to compute for the :attr:`max_norm` option.
                                     Default ``2``.
        scale_grad_by_freq (boolean, optional): if given, this will scale gradients by the inverse of frequency of
                                                the words in the mini-batch. Default ``False``.
                                                Note: this option is not supported when ``mode="max"``.
        mode (string, optional): ``"sum"``, ``"mean"`` or ``"max"``. Specifies the way to reduce the bag.
                                 Default: ``"mean"``
        sparse (bool, optional): if ``True``, gradient w.r.t. :attr:`weight` will be a sparse tensor. See Notes under
                                 :class:`torch.nn.Embedding` for more details regarding sparse gradients.
                                 Note: this option is not supported when ``mode="max"``.
        per_sample_weights (Tensor, optional): a tensor of float / double weights, or None
            to indicate all weights should be taken to be 1. If specified, :attr:`per_sample_weights`
            must have exactly the same shape as input and is treated as having the same
            :attr:`offsets`, if those are not None.

        include_last_offset (bool, optional): if ``True``, the size of offsets is equal to the number of bags + 1.
        The last element is the size of the input, or the ending index position of the last bag (sequence).


    Shape:

        - :attr:`input` (LongTensor) and :attr:`offsets` (LongTensor, optional)

          - If :attr:`input` is 2D of shape `(B, N)`,

            it will be treated as ``B`` bags (sequences) each of fixed length ``N``, and
            this will return ``B`` values aggregated in a way depending on the :attr:`mode`.
            :attr:`offsets` is ignored and required to be ``None`` in this case.

          - If :attr:`input` is 1D of shape `(N)`,

            it will be treated as a concatenation of multiple bags (sequences).
            :attr:`offsets` is required to be a 1D tensor containing the
            starting index positions of each bag in :attr:`input`. Therefore,
            for :attr:`offsets` of shape `(B)`, :attr:`input` will be viewed as
            having ``B`` bags. Empty bags (i.e., having 0-length) will have
            returned vectors filled by zeros.

        - :attr:`weight` (Tensor): the learnable weights of the module of
          shape `(num_embeddings, embedding_dim)`

        - :attr:`per_sample_weights` (Tensor, optional). Has the same shape as
          :attr:`input`.

        - :attr:`output`: aggregated embedding values of shape `(B, embedding_dim)`

    Examples::

        >>> # an Embedding module containing 10 tensors of size 3
        >>> embedding_matrix = torch.rand(10, 3)
        >>> # a batch of 2 samples of 4 indices each
        >>> input = torch.tensor([1,2,4,5,4,3,2,9])
        >>> offsets = torch.tensor([0,4])
        >>> F.embedding_bag(embedding_matrix, input, offsets)
        tensor([[ 0.3397,  0.3552,  0.5545],
                [ 0.5893,  0.4386,  0.5882]])
    c                 S   s   g | ]}t |ƒtu‘qS r.   rÚ   rÛ   r.   r.   r/   rÞ   ‘  rß   z!embedding_bag.<locals>.<listcomp>)Úoffsetsrì   rk   rñ   Úmoderò   Úper_sample_weightsÚinclude_last_offsetzªArgument order of nn.functional.embedding_bag was changed. Usage `embedding_bag(weight, input, ...)` is deprecated, and should now be `embedding_bag(input, weight, ...)`.Nziembedding_bag: If per_sample_weights ({}) is not None, then it must have the same shape as the input ({})r   z	<unknown>z�if input is 2D, then offsets has to be None, as input is treated is a mini-batch of fixed length sequences. However, found offsets of type {}r   r   r   r—   z*offsets has to be a 1D Tensor but got Nonezoffsets has to be a 1D Tensorz?input has to be 1D or 2D Tensor, but got Tensor of dimension {}Úsumró   rÔ   z?max mode does not support scaling the gradient by the frequencyz(max mode does not support sparse weightsz&mode has to be one of sum, mean or maxz�embedding_bag: per_sample_weights was not None. per_sample_weights is only supported for mode='sum' (got mode='{}'). Please open a feature request on GitHub.)r   r   r    rá   r   r   Úembedding_bagr   ÚlongÚis_floating_pointrÁ   rÂ   r&   r$   rR   Úshaper˜   Ústrr!   ZarangeÚnumelr   Zreshaperí   ÚNotImplementedError)r,   r±   rô   rì   rk   rñ   rõ   rò   rö   r÷   rä   Ztype_strÚ	mode_enumrT   Ú_r.   r.   r/   rù   ?  s„    P
ü

þ
ýÿ



ÿ




ýø	rù   c                 C   sH   | d }t t| ƒd ƒD ]}|| |d  9 }q|dkrDtd | ¡ƒ‚d S )Nr   r   r   zGExpected more than 1 value per channel when training, got input size {})rO   rP   r$   rR   )r&   Z
size_prodsÚir.   r.   r/   Ú_verify_batch_sizeæ  s
    r  çš™™™™™¹?çñhãˆµøä>c                 C   sn   t j ¡ s>t| ƒtur>t| fƒr>tt| f| |||||||d�
S |rNt|  	¡ ƒ t  | |||||||t j
jj¡	S )zÂApplies Batch Normalization for each channel across a batch of data.

    See :class:`~torch.nn.BatchNorm1d`, :class:`~torch.nn.BatchNorm2d`,
    :class:`~torch.nn.BatchNorm3d` for details.
    )r±   rà   r‚   ÚmomentumrÏ   )r   r   r    r!   r"   r   r   Ú
batch_normr  r&   ÚbackendsÚcudnnÚenabled)r,   Úrunning_meanÚrunning_varr±   rà   r‚   r  rÏ   r.   r.   r/   r  ø  s    
þ
þr  c                 C   sj   t j ¡ s>t| ƒtur>t| fƒr>tt| f| |||||||d�
S t|  	¡ ƒ t  | |||||||t j
jj¡	S )zÚApplies Instance Normalization for each channel in each data sample in a
    batch.

    See :class:`~torch.nn.InstanceNorm1d`, :class:`~torch.nn.InstanceNorm2d`,
    :class:`~torch.nn.InstanceNorm3d` for details.
    )r  r  r±   rà   Úuse_input_statsr  rÏ   )r   r   r    r!   r"   r   r   Úinstance_normr  r&   r  r	  r
  )r,   r  r  r±   rà   r  r  rÏ   r.   r.   r/   r    s    	

ý
þr  c              	   C   sR   t j ¡ s8t| ƒtur8t| fƒr8tt| f| ||||d�S t  | ||||t jj	j
¡S )zzApplies Layer Normalization for last certain number of dimensions.

    See :class:`~torch.nn.LayerNorm` for details.
    ©r±   rà   rÏ   )r   r   r    r!   r"   r   r   Ú
layer_normr  r	  r
  )r,   Znormalized_shaper±   rà   rÏ   r.   r.   r/   r  $  s    
ÿÿr  c              	   C   s†   t j ¡ s8t| ƒtur8t| fƒr8tt| f| ||||d�S t|  	d¡|  	d¡ | |gt
|  	¡ dd… ƒ ƒ t  | ||||t jjj¡S )zzApplies Group Normalization for last certain number of dimensions.

    See :class:`~torch.nn.GroupNorm` for details.
    r  r   r   r   N)r   r   r    r!   r"   r   r   Ú
group_normr  r&   rZ   r  r	  r
  )r,   Z
num_groupsr±   rà   rÏ   r.   r.   r/   r  2  s    
ÿÿþÿr  ç-Cëâ6?ç      è?c              	   C   s0  t j ¡ s8t| ƒtur8t| fƒr8tt| f| ||||d�S |  ¡ }|dk rVt	d 
|¡ƒ‚|  | ¡ d¡}|dkr¦t|dd|d |d d fƒ}t||dfdd� d¡}nl|  ¡ }| |d d|d |d d¡}t|dddd|d |d d fƒ}t||ddfdd� d¡}| |¡}| |¡ |¡ |¡}| | S )	zöApplies local response normalization over an input signal composed of
    several input planes, where channels occupy the second dimension.
    Applies normalization across channels.

    See :class:`~torch.nn.LocalResponseNorm` for details.
    )r¤   ÚbetaÚkr   zWExpected 3D or higher dimensionality                          input (got {} dimensions)r   r   r   )r>   r—   )r   r   r    r!   r"   r   r   Úlocal_response_normr˜   r$   rR   rj   r\   Úpadre   r]   r&   ÚviewÚ
avg_pool3dÚaddrf   )r,   r&   r¤   r  r  r˜   ÚdivÚsizesr.   r.   r/   r  C  s*    
ÿÿ"
r  c              
   C   s   t  | ||||t |¡|¡S )aì	  The Connectionist Temporal Classification loss.

    See :class:`~torch.nn.CTCLoss` for details.

    Note:
        In some circumstances when using the CUDA backend with CuDNN, this operator
        may select a nondeterministic algorithm to increase performance. If this is
        undesirable, you can try to make the operation deterministic (potentially at
        a performance cost) by setting ``torch.backends.cudnn.deterministic =
        True``.
        Please see the notes on :doc:`/notes/randomness` for background.

    Note:
        When using the CUDA backend, this operation may induce nondeterministic
        behaviour in its backward pass that is not easily switched off.
        Please see the notes on :doc:`/notes/randomness` for background.

    Args:
        log_probs: :math:`(T, N, C)` where `C = number of characters in alphabet including blank`,
            `T = input length`, and `N = batch size`.
            The logarithmized probabilities of the outputs
            (e.g. obtained with :func:`torch.nn.functional.log_softmax`).
        targets: :math:`(N, S)` or `(sum(target_lengths))`.
            Targets cannot be blank. In the second form, the targets are assumed to be concatenated.
        input_lengths: :math:`(N)`.
            Lengths of the inputs (must each be :math:`\leq T`)
        target_lengths: :math:`(N)`.
            Lengths of the targets
        blank (int, optional):
            Blank label. Default :math:`0`.
        reduction (string, optional): Specifies the reduction to apply to the output:
            ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
            ``'mean'``: the output losses will be divided by the target lengths and
            then the mean over the batch is taken, ``'sum'``: the output will be
            summed. Default: ``'mean'``
        zero_infinity (bool, optional):
            Whether to zero infinite losses and the associated gradients.
            Default: ``False``
            Infinite losses mainly occur when the inputs are too short
            to be aligned to the targets.

    Example::

        >>> log_probs = torch.randn(50, 16, 20).log_softmax(2).detach().requires_grad_()
        >>> targets = torch.randint(1, 20, (16, 30), dtype=torch.long)
        >>> input_lengths = torch.full((16,), 50, dtype=torch.long)
        >>> target_lengths = torch.randint(10,30,(16,), dtype=torch.long)
        >>> loss = F.ctc_loss(log_probs, targets, input_lengths, target_lengths)
        >>> loss.backward()
    )r   Úctc_lossÚ
_ReductionÚget_enum)Z	log_probsÚtargetsZinput_lengthsZtarget_lengthsZblankÚ	reductionZzero_infinityr.   r.   r/   r  c  s    5ÿr  éœÿÿÿc                 C   s  t j ¡ sF| |f}tdd„ |D ƒƒrFt|ƒrFtt|| ||||||d�	S |dusV|durbt ||¡}|  	¡ }|dk r€t
d |¡ƒ‚|  d¡| d¡kr°t
d |  d¡| d¡¡ƒ‚|dkrØt jj | ||t |¡|¡}	�nB|d	k�rt jj | ||t |¡|¡}	�n|  d¡}
|  d
¡}|
f|  ¡ dd…  }| ¡ d
d… |  ¡ dd… k�rbt
d || ¡ ¡ƒ‚|  ¡ } | ¡ }|  ¡ dk�r’|  |
|d
d¡} n|  |
|dd¡} | ¡ dk�rÀ| |
d
d¡}n| |
dd¡}t |¡}|dk�rút jj | ||||¡}	n t jj | ||||¡}| |¡}	|	S )aì	  The negative log likelihood loss.

    See :class:`~torch.nn.NLLLoss` for details.

    Args:
        input: :math:`(N, C)` where `C = number of classes` or :math:`(N, C, H, W)`
            in case of 2D Loss, or :math:`(N, C, d_1, d_2, ..., d_K)` where :math:`K \geq 1`
            in the case of K-dimensional loss.
        target: :math:`(N)` where each value is :math:`0 \leq \text{targets}[i] \leq C-1`,
            or :math:`(N, d_1, d_2, ..., d_K)` where :math:`K \geq 1` for
            K-dimensional loss.
        weight (Tensor, optional): a manual rescaling weight given to each
            class. If given, has to be a Tensor of size `C`
        size_average (bool, optional): Deprecated (see :attr:`reduction`). By default,
            the losses are averaged over each loss element in the batch. Note that for
            some losses, there multiple elements per sample. If the field :attr:`size_average`
            is set to ``False``, the losses are instead summed for each minibatch. Ignored
            when reduce is ``False``. Default: ``True``
        ignore_index (int, optional): Specifies a target value that is ignored
            and does not contribute to the input gradient. When :attr:`size_average` is
            ``True``, the loss is averaged over non-ignored targets. Default: -100
        reduce (bool, optional): Deprecated (see :attr:`reduction`). By default, the
            losses are averaged or summed over observations for each minibatch depending
            on :attr:`size_average`. When :attr:`reduce` is ``False``, returns a loss per
            batch element instead and ignores :attr:`size_average`. Default: ``True``
        reduction (string, optional): Specifies the reduction to apply to the output:
            ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
            ``'mean'``: the sum of the output will be divided by the number of
            elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average`
            and :attr:`reduce` are in the process of being deprecated, and in the meantime,
            specifying either of those two args will override :attr:`reduction`. Default: ``'mean'``

    Example::

        >>> # input is of size N x C = 3 x 5
        >>> input = torch.randn(3, 5, requires_grad=True)
        >>> # each element in target has to have 0 <= value < C
        >>> target = torch.tensor([1, 0, 4])
        >>> output = F.nll_loss(F.log_softmax(input), target)
        >>> output.backward()
    c                 S   s   g | ]}t |ƒtu‘qS r.   rÚ   rÛ   r.   r.   r/   rÞ   Ê  rß   znll_loss.<locals>.<listcomp>©r±   Úsize_averageÚignore_indexÚreducer!  Nr   z&Expected 2 or more dimensions (got {})r   z?Expected input batch_size ({}) to match target batch_size ({}).r3   r   zExpected target size {}, got {}r—   Únone)r   r   r    rá   r   r   Únll_lossr  Úlegacy_get_stringr˜   r$   rR   r&   r(   r)   r  Z
nll_loss2drï   rþ   r  )r,   Útargetr±   r$  r%  r&  r!  rä   r˜   rT   ÚnÚcZout_sizeÚreduction_enumrm   r.   r.   r/   r(  œ  sZ    ,
þÿ 
 

"ÿ


ÿ
ÿ
r(  ç:Œ0âŽyE>c           
      C   sª   t j ¡ sH| |f}tdd„ |D ƒƒrHt|ƒrHtt|| |||||||d�
S |dusX|durdt ||¡}|dkrŒ|dkrŒ|dkrŒ| }	t	|d ƒ‚t  | ||||t 
|¡¡}	|	S )	aŒ  Poisson negative log likelihood loss.

    See :class:`~torch.nn.PoissonNLLLoss` for details.

    Args:
        input: expectation of underlying Poisson distribution.
        target: random sample :math:`target \sim \text{Poisson}(input)`.
        log_input: if ``True`` the loss is computed as
            :math:`\exp(\text{input}) - \text{target} * \text{input}`, if ``False`` then loss is
            :math:`\text{input} - \text{target} * \log(\text{input}+\text{eps})`. Default: ``True``
        full: whether to compute full loss, i. e. to add the Stirling
            approximation term. Default: ``False``
            :math:`\text{target} * \log(\text{target}) - \text{target} + 0.5 * \log(2 * \pi * \text{target})`.
        size_average (bool, optional): Deprecated (see :attr:`reduction`). By default,
            the losses are averaged over each loss element in the batch. Note that for
            some losses, there multiple elements per sample. If the field :attr:`size_average`
            is set to ``False``, the losses are instead summed for each minibatch. Ignored
            when reduce is ``False``. Default: ``True``
        eps (float, optional): Small value to avoid evaluation of :math:`\log(0)` when
            :attr:`log_input`=``False``. Default: 1e-8
        reduce (bool, optional): Deprecated (see :attr:`reduction`). By default, the
            losses are averaged or summed over observations for each minibatch depending
            on :attr:`size_average`. When :attr:`reduce` is ``False``, returns a loss per
            batch element instead and ignores :attr:`size_average`. Default: ``True``
        reduction (string, optional): Specifies the reduction to apply to the output:
            ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
            ``'mean'``: the sum of the output will be divided by the number of
            elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average`
            and :attr:`reduce` are in the process of being deprecated, and in the meantime,
            specifying either of those two args will override :attr:`reduction`. Default: ``'mean'``

    c                 S   s   g | ]}t |ƒtu‘qS r.   rÚ   rÛ   r.   r.   r/   rÞ   	  rß   z$poisson_nll_loss.<locals>.<listcomp>)Ú	log_inputÚfullr$  rÏ   r&  r!  Nr'  ró   rø   ú is not valid)r   r   r    rá   r   r   Úpoisson_nll_lossr  r)  r$   r  )
r,   r*  r/  r0  r$  rÏ   r&  r!  rä   rT   r.   r.   r/   r2  ù  s    #
þr2  c           	   
   C   sÌ   t j ¡ sD| |f}tdd„ |D ƒƒrDt|ƒrDtt|| |||||d�S |dusT|durbt ||¡}n0|dkrtt	 
d¡ |dkrˆt d¡}n
t |¡}t j| |||d	�}|dkrÈ|  ¡ d
krÈ||  ¡ d
  }|S )aÙ  The `Kullback-Leibler divergence Loss
    <https://en.wikipedia.org/wiki/Kullback-Leibler_divergence>`__

    See :class:`~torch.nn.KLDivLoss` for details.

    Args:
        input: Tensor of arbitrary shape
        target: Tensor of the same shape as input
        size_average (bool, optional): Deprecated (see :attr:`reduction`). By default,
            the losses are averaged over each loss element in the batch. Note that for
            some losses, there multiple elements per sample. If the field :attr:`size_average`
            is set to ``False``, the losses are instead summed for each minibatch. Ignored
            when reduce is ``False``. Default: ``True``
        reduce (bool, optional): Deprecated (see :attr:`reduction`). By default, the
            losses are averaged or summed over observations for each minibatch depending
            on :attr:`size_average`. When :attr:`reduce` is ``False``, returns a loss per
            batch element instead and ignores :attr:`size_average`. Default: ``True``
        reduction (string, optional): Specifies the reduction to apply to the output:
            ``'none'`` | ``'batchmean'`` | ``'sum'`` | ``'mean'``.
            ``'none'``: no reduction will be applied
            ``'batchmean'``: the sum of the output will be divided by the batchsize
            ``'sum'``: the output will be summed
            ``'mean'``: the output will be divided by the number of elements in the output
            Default: ``'mean'``
        log_target (bool): A flag indicating whether ``target`` is passed in the log space.
            It is recommended to pass certain distributions (like ``softmax``)
            in the log space to avoid numerical issues caused by explicit ``log``.
            Default: ``False``

    .. note::
        :attr:`size_average` and :attr:`reduce` are in the process of being deprecated,
        and in the meantime, specifying either of those two args will override :attr:`reduction`.

    .. note::
        :attr:``reduction`` = ``'mean'`` doesn't return the true kl divergence value, please use
        :attr:``reduction`` = ``'batchmean'`` which aligns with KL math definition.
        In the next major release, ``'mean'`` will be changed to be the same as 'batchmean'.
    c                 S   s   g | ]}t |ƒtu‘qS r.   rÚ   rÛ   r.   r.   r/   rÞ   V	  rß   zkl_div.<locals>.<listcomp>)r$  r&  r!  Ú
log_targetNró   zÿreduction: 'mean' divides the total loss by both the batch size and the support size.'batchmean' divides only by the batch size, and aligns with the KL div math definition.'mean' will be changed to behave the same as 'batchmean' in the next major release.Z	batchmeanrø   )r3  r   )r   r   r    rá   r   r   Úkl_divr  Úlegacy_get_enumrÁ   rÂ   r  r˜   r&   )	r,   r*  r$  r&  r!  r3  rä   r-  Zreducedr.   r.   r/   r4  ,	  s$    (

þ

r4  c                 C   s|   t j ¡ sF| |f}tdd„ |D ƒƒrFt|ƒrFtt|| ||||||d�	S |dusV|durbt ||¡}t	t
| dƒ||d|d|ƒS )aÎ	  This criterion combines `log_softmax` and `nll_loss` in a single
    function.

    See :class:`~torch.nn.CrossEntropyLoss` for details.

    Args:
        input (Tensor) : :math:`(N, C)` where `C = number of classes` or :math:`(N, C, H, W)`
            in case of 2D Loss, or :math:`(N, C, d_1, d_2, ..., d_K)` where :math:`K \geq 1`
            in the case of K-dimensional loss.
        target (Tensor) : :math:`(N)` where each value is :math:`0 \leq \text{targets}[i] \leq C-1`,
            or :math:`(N, d_1, d_2, ..., d_K)` where :math:`K \geq 1` for
            K-dimensional loss.
        weight (Tensor, optional): a manual rescaling weight given to each
            class. If given, has to be a Tensor of size `C`
        size_average (bool, optional): Deprecated (see :attr:`reduction`). By default,
            the losses are averaged over each loss element in the batch. Note that for
            some losses, there multiple elements per sample. If the field :attr:`size_average`
            is set to ``False``, the losses are instead summed for each minibatch. Ignored
            when reduce is ``False``. Default: ``True``
        ignore_index (int, optional): Specifies a target value that is ignored
            and does not contribute to the input gradient. When :attr:`size_average` is
            ``True``, the loss is averaged over non-ignored targets. Default: -100
        reduce (bool, optional): Deprecated (see :attr:`reduction`). By default, the
            losses are averaged or summed over observations for each minibatch depending
            on :attr:`size_average`. When :attr:`reduce` is ``False``, returns a loss per
            batch element instead and ignores :attr:`size_average`. Default: ``True``
        reduction (string, optional): Specifies the reduction to apply to the output:
            ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
            ``'mean'``: the sum of the output will be divided by the number of
            elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average`
            and :attr:`reduce` are in the process of being deprecated, and in the meantime,
            specifying either of those two args will override :attr:`reduction`. Default: ``'mean'``

    Examples::

        >>> input = torch.randn(3, 5, requires_grad=True)
        >>> target = torch.randint(5, (3,), dtype=torch.int64)
        >>> loss = F.cross_entropy(input, target)
        >>> loss.backward()
    c                 S   s   g | ]}t |ƒtu‘qS r.   rÚ   rÛ   r.   r.   r/   rÞ   �	  rß   z!cross_entropy.<locals>.<listcomp>r#  Nr   )r   r   r    rá   r   r   Úcross_entropyr  r)  r(  r×   )r,   r*  r±   r$  r%  r&  r!  rä   r.   r.   r/   r6  p	  s    +

ýr6  c           	   
   C   sÌ   t j ¡ sD| |f}tdd„ |D ƒƒrDt|ƒrDtt|| |||||d�S |dusT|durbt ||¡}n
t 	|¡}| 
¡ |  
¡ kr”td | 
¡ |  
¡ ¡ƒ‚|dur¸t| 
¡ | 
¡ ƒ}| |¡}t jj | |||¡S )aƒ  Function that measures the Binary Cross Entropy
    between the target and the output.

    See :class:`~torch.nn.BCELoss` for details.

    Args:
        input: Tensor of arbitrary shape
        target: Tensor of the same shape as input
        weight (Tensor, optional): a manual rescaling weight
                if provided it's repeated to match input tensor shape
        size_average (bool, optional): Deprecated (see :attr:`reduction`). By default,
            the losses are averaged over each loss element in the batch. Note that for
            some losses, there multiple elements per sample. If the field :attr:`size_average`
            is set to ``False``, the losses are instead summed for each minibatch. Ignored
            when reduce is ``False``. Default: ``True``
        reduce (bool, optional): Deprecated (see :attr:`reduction`). By default, the
            losses are averaged or summed over observations for each minibatch depending
            on :attr:`size_average`. When :attr:`reduce` is ``False``, returns a loss per
            batch element instead and ignores :attr:`size_average`. Default: ``True``
        reduction (string, optional): Specifies the reduction to apply to the output:
            ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
            ``'mean'``: the sum of the output will be divided by the number of
            elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average`
            and :attr:`reduce` are in the process of being deprecated, and in the meantime,
            specifying either of those two args will override :attr:`reduction`. Default: ``'mean'``

    Examples::

        >>> input = torch.randn((3, 2), requires_grad=True)
        >>> target = torch.rand((3, 2), requires_grad=False)
        >>> loss = F.binary_cross_entropy(F.sigmoid(input), target)
        >>> loss.backward()
    c                 S   s   g | ]}t |ƒtu‘qS r.   rÚ   rÛ   r.   r.   r/   rÞ   Í	  rß   z(binary_cross_entropy.<locals>.<listcomp>©r±   r$  r&  r!  NzwUsing a target size ({}) that is different to the input size ({}) is deprecated. Please ensure they have the same size.)r   r   r    rá   r   r   Úbinary_cross_entropyr  r5  r  r&   r$   rR   r   Úexpandr(   r)   )	r,   r*  r±   r$  r&  r!  rä   r-  Znew_sizer.   r.   r/   r8  §	  s(    $

þ
ÿ
ÿr8  c           	      C   s¨   t j ¡ sF| |f}tdd„ |D ƒƒrFt|ƒrFtt|| ||||||d�	S |dusV|durdt ||¡}n
t 	|¡}| 
¡ |  
¡ ks–td | 
¡ |  
¡ ¡ƒ‚t  | ||||¡S )a	  Function that measures Binary Cross Entropy between target and output
    logits.

    See :class:`~torch.nn.BCEWithLogitsLoss` for details.

    Args:
        input: Tensor of arbitrary shape
        target: Tensor of the same shape as input
        weight (Tensor, optional): a manual rescaling weight
            if provided it's repeated to match input tensor shape
        size_average (bool, optional): Deprecated (see :attr:`reduction`). By default,
            the losses are averaged over each loss element in the batch. Note that for
            some losses, there multiple elements per sample. If the field :attr:`size_average`
            is set to ``False``, the losses are instead summed for each minibatch. Ignored
            when reduce is ``False``. Default: ``True``
        reduce (bool, optional): Deprecated (see :attr:`reduction`). By default, the
            losses are averaged or summed over observations for each minibatch depending
            on :attr:`size_average`. When :attr:`reduce` is ``False``, returns a loss per
            batch element instead and ignores :attr:`size_average`. Default: ``True``
        reduction (string, optional): Specifies the reduction to apply to the output:
            ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
            ``'mean'``: the sum of the output will be divided by the number of
            elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average`
            and :attr:`reduce` are in the process of being deprecated, and in the meantime,
            specifying either of those two args will override :attr:`reduction`. Default: ``'mean'``
        pos_weight (Tensor, optional): a weight of positive examples.
                Must be a vector with length equal to the number of classes.

    Examples::

         >>> input = torch.randn(3, requires_grad=True)
         >>> target = torch.empty(3).random_(2)
         >>> loss = F.binary_cross_entropy_with_logits(input, target)
         >>> loss.backward()
    c                 S   s   g | ]}t |ƒtu‘qS r.   rÚ   rÛ   r.   r.   r/   rÞ   	
  rß   z4binary_cross_entropy_with_logits.<locals>.<listcomp>)r±   r$  r&  r!  Ú
pos_weightNz4Target size ({}) must be the same as input size ({}))r   r   r    rá   r   r   Ú binary_cross_entropy_with_logitsr  r5  r  r&   r$   rR   )	r,   r*  r±   r$  r&  r!  r:  rä   r-  r.   r.   r/   r;  á	  s    &

ý
r;  c           	   
   C   s¸   t j ¡ sD| |f}tdd„ |D ƒƒrDt|ƒrDtt|| |||||d�S | ¡ |  ¡ ksrtj	d 
| ¡ |  ¡ ¡dd� |dus‚|durŽt ||¡}t  | |¡\}}t jj ||t |¡|¡S )z®Function that uses a squared term if the absolute
    element-wise error falls below beta and an L1 term otherwise.

    See :class:`~torch.nn.SmoothL1Loss` for details.
    c                 S   s   g | ]}t |ƒtu‘qS r.   rÚ   rÛ   r.   r.   r/   rÞ   "
  rß   z"smooth_l1_loss.<locals>.<listcomp>)r$  r&  r!  r  ú©Using a target size ({}) that is different to the input size ({}). This will likely lead to incorrect results due to broadcasting. Please ensure they have the same size.r   r¿   N)r   r   r    rá   r   r   Úsmooth_l1_lossr&   rÁ   rÂ   rR   r  r)  Úbroadcast_tensorsr(   r)   r  )	r,   r*  r$  r&  r!  r  rä   Úexpanded_inputÚexpanded_targetr.   r.   r/   r=  
  s"    

þþýr=  c              	   C   s´   t j ¡ sB| |f}tdd„ |D ƒƒrBt|ƒrBtt|| ||||d�S | ¡ |  ¡ ksptj	d 
| ¡ |  ¡ ¡dd� |dus€|durŒt ||¡}t  | |¡\}}t jj ||t |¡¡S )zÑl1_loss(input, target, size_average=None, reduce=None, reduction='mean') -> Tensor

    Function that takes the mean element-wise absolute value difference.

    See :class:`~torch.nn.L1Loss` for details.
    c                 S   s   g | ]}t |ƒtu‘qS r.   rÚ   rÛ   r.   r.   r/   rÞ   <
  rß   zl1_loss.<locals>.<listcomp>©r$  r&  r!  r<  r   r¿   N)r   r   r    rá   r   r   Úl1_lossr&   rÁ   rÂ   rR   r  r)  r>  r(   r)   r  ©r,   r*  r$  r&  r!  rä   r?  r@  r.   r.   r/   rB  2
  s"    
þþýrB  c              	   C   s´   t j ¡ sB| |f}tdd„ |D ƒƒrBt|ƒrBtt|| ||||d�S | ¡ |  ¡ ksptj	d 
| ¡ |  ¡ ¡dd� |dus€|durŒt ||¡}t  | |¡\}}t jj ||t |¡¡S )z¼mse_loss(input, target, size_average=None, reduce=None, reduction='mean') -> Tensor

    Measures the element-wise mean squared error.

    See :class:`~torch.nn.MSELoss` for details.
    c                 S   s   g | ]}t |ƒtu‘qS r.   rÚ   rÛ   r.   r.   r/   rÞ   W
  rß   zmse_loss.<locals>.<listcomp>rA  r<  r   r¿   N)r   r   r    rá   r   r   Úmse_lossr&   rÁ   rÂ   rR   r  r)  r>  r(   r)   r  rC  r.   r.   r/   rD  M
  s"    
þþýrD  c           	      C   sÄ   t j ¡ sH| ||f}tdd„ |D ƒƒrHt|ƒrHtt|| ||||||d�	S |dusX|durft ||¡}n
t 	|¡}|  
¡ dks”| 
¡ dks”| 
¡ dkr²td |  ¡ | ¡ | ¡ ¡ƒ‚t  | ||||¡S )z±margin_ranking_loss(input1, input2, target, margin=0, size_average=None, reduce=None, reduction='mean') -> Tensor

    See :class:`~torch.nn.MarginRankingLoss` for details.
    c                 S   s   g | ]}t |ƒtu‘qS r.   rÚ   rÛ   r.   r.   r/   rÞ   p
  rß   z'margin_ranking_loss.<locals>.<listcomp>©Úmarginr$  r&  r!  Nr   z\margin_ranking_loss does not support scalars, got sizes: input1: {}, input2: {}, target: {} )r   r   r    rá   r   r   Úmargin_ranking_lossr  r5  r  r˜   r›   rR   r&   ©	rç   rè   r*  rF  r$  r&  r!  rä   r-  r.   r.   r/   rG  g
  s    

þ
$ÿrG  c              
   C   s|   t j ¡ sD| |f}tdd„ |D ƒƒrDt|ƒrDtt|| |||||d�S |dusT|durbt ||¡}n
t 	|¡}t  | |||¡S )z¬hinge_embedding_loss(input, target, margin=1.0, size_average=None, reduce=None, reduction='mean') -> Tensor

    See :class:`~torch.nn.HingeEmbeddingLoss` for details.
    c                 S   s   g | ]}t |ƒtu‘qS r.   rÚ   rÛ   r.   r.   r/   rÞ   ‡
  rß   z(hinge_embedding_loss.<locals>.<listcomp>rE  N)
r   r   r    rá   r   r   Úhinge_embedding_lossr  r5  r  )r,   r*  rF  r$  r&  r!  rä   r-  r.   r.   r/   rI  ~
  s    

þ
rI  c              	   C   s|   t j ¡ sB| |f}tdd„ |D ƒƒrBt|ƒrBtt|| ||||d�S |dusR|dur`t ||¡}n
t 	|¡}t j
j | ||¡S )z¤multilabel_margin_loss(input, target, size_average=None, reduce=None, reduction='mean') -> Tensor

    See :class:`~torch.nn.MultiLabelMarginLoss` for details.
    c                 S   s   g | ]}t |ƒtu‘qS r.   rÚ   rÛ   r.   r.   r/   rÞ   š
  rß   z*multilabel_margin_loss.<locals>.<listcomp>rA  N)r   r   r    rá   r   r   Úmultilabel_margin_lossr  r5  r  r(   r)   ©r,   r*  r$  r&  r!  rä   r-  r.   r.   r/   rJ  ’
  s    

þ
rJ  c              	   C   s|   t j ¡ sB| |f}tdd„ |D ƒƒrBt|ƒrBtt|| ||||d�S |dusR|dur`t ||¡}n
t 	|¡}t j
j | ||¡S )z˜soft_margin_loss(input, target, size_average=None, reduce=None, reduction='mean') -> Tensor

    See :class:`~torch.nn.SoftMarginLoss` for details.
    c                 S   s   g | ]}t |ƒtu‘qS r.   rÚ   rÛ   r.   r.   r/   rÞ   ­
  rß   z$soft_margin_loss.<locals>.<listcomp>rA  N)r   r   r    rá   r   r   Úsoft_margin_lossr  r5  r  r(   r)   rK  r.   r.   r/   rL  ¥
  s    

þ
rL  c           	   
   C   sì   t j ¡ sD| |f}tdd„ |D ƒƒrDt|ƒrDtt|| |||||d�S |dusT|dur`t ||¡}|t	| ƒ d| t	|  ƒ   }|dur�|| }|j
dd�|  d¡ }|dkr´|}n4|dkrÆ| ¡ }n"|d	krØ| 
¡ }n| }t|d
 ƒ‚|S )z›multilabel_soft_margin_loss(input, target, weight=None, size_average=None) -> Tensor

    See :class:`~torch.nn.MultiLabelSoftMarginLoss` for details.
    c                 S   s   g | ]}t |ƒtu‘qS r.   rÚ   rÛ   r.   r.   r/   rÞ   Á
  rß   z/multilabel_soft_margin_loss.<locals>.<listcomp>r7  Nr   r™   r'  ró   rø   r1  )r   r   r    rá   r   r   Úmultilabel_soft_margin_lossr  r)  Ú
logsigmoidrø   r&   ró   r$   )	r,   r*  r±   r$  r&  r!  rä   ZlossrT   r.   r.   r/   rM  ¸
  s,    

þ 

rM  c           	      C   s‚   t j ¡ sH| ||f}tdd„ |D ƒƒrHt|ƒrHtt|| ||||||d�	S |dusX|durft ||¡}n
t 	|¡}t  | ||||¡S )zµcosine_embedding_loss(input1, input2, target, margin=0, size_average=None, reduce=None, reduction='mean') -> Tensor

    See :class:`~torch.nn.CosineEmbeddingLoss` for details.
    c                 S   s   g | ]}t |ƒtu‘qS r.   rÚ   rÛ   r.   r.   r/   rÞ   ä
  rß   z)cosine_embedding_loss.<locals>.<listcomp>rE  N)
r   r   r    rá   r   r   Úcosine_embedding_lossr  r5  r  rH  r.   r.   r/   rO  Û
  s    

þ
rO  c           
      C   s¼   t j ¡ sH| |f}tdd„ |D ƒƒrHt|ƒrHtt|| |||||||d�
S |dusX|durft ||¡}	n
t 	|¡}	|dkrˆ|dkrˆt
dƒ‚|dur¤| ¡ dkr¤t
dƒ‚t jj | |||||	¡S )	zÐmulti_margin_loss(input, target, p=1, margin=1, weight=None, size_average=None,
                          reduce=None, reduction='mean') -> Tensor

    See :class:`~torch.nn.MultiMarginLoss` for details.
    c                 S   s   g | ]}t |ƒtu‘qS r.   rÚ   rÛ   r.   r.   r/   rÞ   ù
  rß   z%multi_margin_loss.<locals>.<listcomp>)r�   rF  r±   r$  r&  r!  Nr   r   z only p == 1 and p == 2 supportedzweight must be one-dimensional)r   r   r    rá   r   r   Úmulti_margin_lossr  r5  r  r$   r˜   r(   r)   )
r,   r*  r�   rF  r±   r$  r&  r!  rä   r-  r.   r.   r/   rP  ï
  s"    
ý
rP  aÖ  
Rearranges elements in a tensor of shape :math:`(*, C \times r^2, H, W)` to a
tensor of shape :math:`(*, C, H \times r, W \times r)`.

See :class:`~torch.nn.PixelShuffle` for details.

Args:
    input (Tensor): the input tensor
    upscale_factor (int): factor to increase spatial resolution by

Examples::

    >>> input = torch.randn(1, 9, 4, 4)
    >>> output = torch.nn.functional.pixel_shuffle(input, 3)
    >>> print(output.size())
    torch.Size([1, 1, 12, 12])
a  
Divide the channels in a tensor of shape :math:`(*, C , H, W)`
into g groups and rearrange them as :math:`(*, C \frac g, g, H, W)`,
while keeping the original tensor shape.

See :class:`~torch.nn.ChannelShuffle` for details.

Args:
    input (Tensor): the input tensor
    groups (int): number of groups to divide channels in and rearrange.

Examples::

    >>> input = torch.randn(1, 4, 2, 2)
    >>> print(input)
    [[[[1, 2],
       [3, 4]],
      [[5, 6],
       [7, 8]],
      [[9, 10],
       [11, 12]],
      [[13, 14],
       [15, 16]],
     ]]
    >>> output = torch.nn.functional.channel_shuffle(input, 2)
    >>> print(output)
    [[[[1, 2],
       [3, 4]],
      [[9, 10],
       [11, 12]],
      [[5, 6],
       [7, 8]],
      [[13, 14],
       [15, 16]],
     ]]
Únearestc                 C   s   d S rë   r.   ©r,   r&   Úscale_factorrõ   Úalign_cornersr.   r.   r/   ÚupsampleB  s    rU  c                 C   s   d S rë   r.   rR  r.   r.   r/   rU  G  s    c                 C   s   t  d¡ t| ||||ƒS )aÞ  Upsamples the input to either the given :attr:`size` or the given
    :attr:`scale_factor`

    .. warning::
        This function is deprecated in favor of :func:`torch.nn.functional.interpolate`.
        This is equivalent with ``nn.functional.interpolate(...)``.

    Note:
        When using the CUDA backend, this operation may induce nondeterministic
        behaviour in its backward pass that is not easily switched off.
        Please see the notes on :doc:`/notes/randomness` for background.

    The algorithm used for upsampling is determined by :attr:`mode`.

    Currently temporal, spatial and volumetric upsampling are supported, i.e.
    expected inputs are 3-D, 4-D or 5-D in shape.

    The input dimensions are interpreted in the form:
    `mini-batch x channels x [optional depth] x [optional height] x width`.

    The modes available for upsampling are: `nearest`, `linear` (3D-only),
    `bilinear`, `bicubic` (4D-only), `trilinear` (5D-only)

    Args:
        input (Tensor): the input tensor
        size (int or Tuple[int] or Tuple[int, int] or Tuple[int, int, int]):
            output spatial size.
        scale_factor (float or Tuple[float]): multiplier for spatial size. Has to match input size if it is a tuple.
        mode (string): algorithm used for upsampling:
            ``'nearest'`` | ``'linear'`` | ``'bilinear'`` | ``'bicubic'`` |
            ``'trilinear'``. Default: ``'nearest'``
        align_corners (bool, optional): Geometrically, we consider the pixels of the
            input and output as squares rather than points.
            If set to ``True``, the input and output tensors are aligned by the
            center points of their corner pixels, preserving the values at the corner pixels.
            If set to ``False``, the input and output tensors are aligned by the corner
            points of their corner pixels, and the interpolation uses edge value padding
            for out-of-boundary values, making this operation *independent* of input size
            when :attr:`scale_factor` is kept the same. This only has an effect when :attr:`mode`
            is ``'linear'``, ``'bilinear'``, ``'bicubic'`` or ``'trilinear'``.
            Default: ``False``

    .. note::
        With ``mode='bicubic'``, it's possible to cause overshoot, in other words it can produce
        negative values or values greater than 255 for images.
        Explicitly call ``result.clamp(min=0, max=255)`` if you want to reduce the overshoot
        when displaying the image.

    .. warning::
        With ``align_corners = True``, the linearly interpolating modes
        (`linear`, `bilinear`, and `trilinear`) don't proportionally align the
        output and input pixels, and thus the output values can depend on the
        input size. This was the default behavior for these modes up to version
        0.3.1. Since then, the default behavior is ``align_corners = False``.
        See :class:`~torch.nn.Upsample` for concrete examples on how this
        affects the outputs.

    zLnn.functional.upsample is deprecated. Use nn.functional.interpolate instead.©rÁ   rÂ   ÚinterpolaterR  r.   r.   r/   rU  M  s    ;
c                 C   s   d S rë   r.   ©r,   r&   rS  rõ   rT  Úrecompute_scale_factorr.   r.   r/   rW  ‹  s    rW  c                 C   s   d S rë   r.   rX  r.   r.   r/   rW  �  s    c                 C   s   d S rë   r.   rX  r.   r.   r/   rW  •  s    c                 C   s   d S rë   r.   rX  r.   r.   r/   rW  š  s    c           	   
      s  t j ¡ s:tˆ ƒtur:tˆ fƒr:ttˆ fˆ ˆˆ|||d�S |dv rT|durptdƒ‚n|du rpt	 
d |¡¡ d}ˆ  ¡ d }ˆdur–ˆdur–tdƒ‚nØˆdurúˆdu sªJ ‚d‰tˆttfƒrâtˆƒ|krÜtd	 |tˆƒ¡ƒ‚ˆ}n‡fd
d„t|ƒD ƒ}ntˆdu�rfˆdu �sJ ‚d}tˆttfƒ�rNtˆƒ|k�rHtd |tˆƒ¡ƒ‚ˆ‰n‡fdd„t|ƒD ƒ‰ntdƒ‚|du �r°ˆdu�rÈˆD ]&}t |¡|k�r†t	 
d¡  �qÈ�q†n|�rÈˆdu�rÈtdƒ‚|dk�rà|du �ràd}|du�rL|�rLt j ¡ �s"t j ¡ �r"‡ ‡fdd„t|ƒD ƒ}n&ˆdu�s0J ‚‡ ‡fdd„t|ƒD ƒ}d‰ˆ  ¡ dk�rv|dk�rvt jj ˆ |ˆ¡S ˆ  ¡ dk�r |dk�r t jj ˆ |ˆ¡S ˆ  ¡ dk�rÊ|dk�rÊt jj ˆ |ˆ¡S ˆ  ¡ dk�rú|dk�rú|du�sðJ ‚tˆ |ƒS ˆ  ¡ dk�r*|dk�r*|du�s J ‚tˆ |ƒS ˆ  ¡ dk�rZ|dk�rZ|du�sPJ ‚tˆ |ƒS ˆ  ¡ dk�r”|dk�r”|du�s€J ‚t jj ˆ ||ˆ¡S ˆ  ¡ dk�rÎ|dk�rÎ|du�sºJ ‚t jj ˆ ||ˆ¡S ˆ  ¡ dk�r|dk�r|du�sôJ ‚t jj ˆ ||ˆ¡S ˆ  ¡ dk�rB|dk�rB|du�s.J ‚t jj  ˆ ||ˆ¡S ˆ  ¡ dk�rb|dk�rbt!dƒ‚ˆ  ¡ dk�r‚|dk�r‚t!dƒ‚ˆ  ¡ dk�r¢|dk�r¢t!dƒ‚ˆ  ¡ dk�rÂ|dk�rÂt!d ƒ‚ˆ  ¡ dk�râ|dk�rât!d!ƒ‚ˆ  ¡ dk�r|dk�rt!d"ƒ‚t!d# ˆ  ¡ |¡ƒ‚dS )$að  Down/up samples the input to either the given :attr:`size` or the given
    :attr:`scale_factor`

    The algorithm used for interpolation is determined by :attr:`mode`.

    Currently temporal, spatial and volumetric sampling are supported, i.e.
    expected inputs are 3-D, 4-D or 5-D in shape.

    The input dimensions are interpreted in the form:
    `mini-batch x channels x [optional depth] x [optional height] x width`.

    The modes available for resizing are: `nearest`, `linear` (3D-only),
    `bilinear`, `bicubic` (4D-only), `trilinear` (5D-only), `area`

    Args:
        input (Tensor): the input tensor
        size (int or Tuple[int] or Tuple[int, int] or Tuple[int, int, int]):
            output spatial size.
        scale_factor (float or Tuple[float]): multiplier for spatial size. Has to match input size if it is a tuple.
        mode (str): algorithm used for upsampling:
            ``'nearest'`` | ``'linear'`` | ``'bilinear'`` | ``'bicubic'`` |
            ``'trilinear'`` | ``'area'``. Default: ``'nearest'``
        align_corners (bool, optional): Geometrically, we consider the pixels of the
            input and output as squares rather than points.
            If set to ``True``, the input and output tensors are aligned by the
            center points of their corner pixels, preserving the values at the corner pixels.
            If set to ``False``, the input and output tensors are aligned by the corner
            points of their corner pixels, and the interpolation uses edge value padding
            for out-of-boundary values, making this operation *independent* of input size
            when :attr:`scale_factor` is kept the same. This only has an effect when :attr:`mode`
            is ``'linear'``, ``'bilinear'``, ``'bicubic'`` or ``'trilinear'``.
            Default: ``False``
        recompute_scale_factor (bool, optional): recompute the scale_factor for use in the
            interpolation calculation.  When `scale_factor` is passed as a parameter, it is used
            to compute the `output_size`.  If `recompute_scale_factor` is ```False`` or not specified,
            the passed-in `scale_factor` will be used in the interpolation computation.
            Otherwise, a new `scale_factor` will be computed based on the output and input sizes for
            use in the interpolation computation (i.e. the computation will be identical to if the computed
            `output_size` were passed-in explicitly).  Note that when `scale_factor` is floating-point,
            the recomputed scale_factor may differ from the one passed in due to rounding and precision
            issues.

    .. note::
        With ``mode='bicubic'``, it's possible to cause overshoot, in other words it can produce
        negative values or values greater than 255 for images.
        Explicitly call ``result.clamp(min=0, max=255)`` if you want to reduce the overshoot
        when displaying the image.

    .. warning::
        With ``align_corners = True``, the linearly interpolating modes
        (`linear`, `bilinear`, and `trilinear`) don't proportionally align the
        output and input pixels, and thus the output values can depend on the
        input size. This was the default behavior for these modes up to version
        0.3.1. Since then, the default behavior is ``align_corners = False``.
        See :class:`~torch.nn.Upsample` for concrete examples on how this
        affects the outputs.

    .. warning::
        When scale_factor is specified, if recompute_scale_factor=True,
        scale_factor is used to compute the output_size which will then
        be used to infer new scales for the interpolation.
        The default behavior for recompute_scale_factor changed to False
        in 1.6.0, and scale_factor is used in the interpolation
        calculation.

    Note:
        When using the CUDA backend, this operation may induce nondeterministic
        behaviour in its backward pass that is not easily switched off.
        Please see the notes on :doc:`/notes/randomness` for background.
    )r&   rS  rõ   rT  rY  )rQ  ÚareaNzjalign_corners option can only be set with the interpolating modes: linear | bilinear | bicubic | trilinearzËDefault upsampling behavior when mode={} is changed to align_corners=False since 0.4.0. Please specify align_corners=True if the old behavior is desired. See the documentation of nn.Upsample for details.Fr   z2only one of size or scale_factor should be definedz;size shape must match input shape. Input is {}D, size is {}c                    s   g | ]}ˆ ‘qS r.   r.   ©rÜ   r  )r&   r.   r/   rÞ     rß   zinterpolate.<locals>.<listcomp>zKscale_factor shape must match input shape. Input is {}D, scale_factor is {}c                    s   g | ]}ˆ ‘qS r.   r.   r[  )rS  r.   r/   rÞ     rß   z-either size or scale_factor should be definedaX  The default behavior for interpolate/upsample with float scale_factor changed in 1.6.0 to align with other frameworks/libraries, and now uses scale_factor directly, instead of relying on the computed output size. If you wish to restore the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. z?recompute_scale_factor is not meaningful with an explicit size.rZ  Tc              	      s<   g | ]4}t  ˆ  |d  ¡ ¡ t jˆ| t jd�  ¡ ¡‘qS )r   rÉ   )r   Úfloorr&   ÚfloatZtensorÚfloat32©rÜ   r  ©r,   Úscale_factorsr.   r/   rÞ   2  s   ÿÿc              
      s0   g | ](}t t tˆ  |d  ¡ƒˆ|  ¡ƒ‘qS )r   )r%   Úmathr\  r]  r&   r_  r`  r.   r/   rÞ   6  rß   r   rQ  r3   é   râ   ræ   Z	trilinearZbicubicz.Got 3D input, but bilinear mode needs 4D inputz/Got 3D input, but trilinear mode needs 5D inputz,Got 4D input, but linear mode needs 3D inputz/Got 4D input, but trilinear mode needs 5D inputz,Got 5D input, but linear mode needs 3D inputz.Got 5D input, but bilinear mode needs 4D inputz‹Input Error: Only 3D, 4D and 5D input Tensors supported (got {}D) for the modes: nearest | linear | bilinear | bicubic | trilinear (got {}))"r   r   r    r!   r"   r   r   rW  r$   rÁ   rÂ   rR   r˜   rY   rZ   ÚtuplerP   rO   rb  r\  r(   Z_get_tracing_stater)   Zupsample_nearest1dZupsample_nearest2dZupsample_nearest3dÚadaptive_avg_pool1dr|   r~   Zupsample_linear1dZupsample_bilinear2dZupsample_trilinear3dZupsample_bicubic2drÿ   )	r,   r&   rS  rõ   rT  rY  r˜   r   Zscaler.   )r,   rS  ra  r&   r/   rW  Ÿ  sÆ    H
ý
ý
ÿ
ÿ


ÿ


þc                 C   s   d S rë   r.   ©r,   r&   rS  r.   r.   r/   Úupsample_nearesth  s    rg  c                 C   s   d S rë   r.   rf  r.   r.   r/   rg  m  s    c                 C   s   t  d¡ t| ||dd�S )a5  Upsamples the input, using nearest neighbours' pixel values.

    .. warning::
        This function is deprecated in favor of :func:`torch.nn.functional.interpolate`.
        This is equivalent with ``nn.functional.interpolate(..., mode='nearest')``.

    Currently spatial and volumetric upsampling are supported (i.e. expected
    inputs are 4 or 5 dimensional).

    Args:
        input (Tensor): input
        size (int or Tuple[int, int] or Tuple[int, int, int]): output spatia
            size.
        scale_factor (int): multiplier for spatial size. Has to be an integer.

    Note:
        When using the CUDA backend, this operation may induce nondeterministic
        behaviour in its backward pass that is not easily switched off.
        Please see the notes on :doc:`/notes/randomness` for background.
    zTnn.functional.upsample_nearest is deprecated. Use nn.functional.interpolate instead.rQ  )rõ   rV  rf  r.   r.   r/   rg  r  s    
c                 C   s   d S rë   r.   rf  r.   r.   r/   Úupsample_bilinear‹  s    rh  c                 C   s   d S rë   r.   rf  r.   r.   r/   rh  �  s    c                 C   s   d S rë   r.   rf  r.   r.   r/   rh  •  s    c                 C   s   d S rë   r.   rf  r.   r.   r/   rh  š  s    c                 C   s   t  d¡ t| ||ddd�S )a!  Upsamples the input, using bilinear upsampling.

    .. warning::
        This function is deprecated in favor of :func:`torch.nn.functional.interpolate`.
        This is equivalent with
        ``nn.functional.interpolate(..., mode='bilinear', align_corners=True)``.

    Expected inputs are spatial (4 dimensional). Use `upsample_trilinear` fo
    volumetric (5 dimensional) inputs.

    Args:
        input (Tensor): input
        size (int or Tuple[int, int]): output spatial size.
        scale_factor (int or Tuple[int, int]): multiplier for spatial size

    Note:
        When using the CUDA backend, this operation may induce nondeterministic
        behaviour in its backward pass that is not easily switched off.
        Please see the notes on :doc:`/notes/randomness` for background.
    zUnn.functional.upsample_bilinear is deprecated. Use nn.functional.interpolate instead.ræ   T)rõ   rT  rV  rf  r.   r.   r/   rh  Ÿ  s    
)ræ   rQ  )ÚzerosÚborderÚ
reflectionri  c              	   C   sà   t j ¡ sB| |f}tdd„ |D ƒƒrBt|ƒrBtt|| ||||d�S |dkr`|dkr`td |¡ƒ‚|dkr†|dkr†|d	kr†td
 |¡ƒ‚|dkr”d}nd}|dkr¦d}n|dkr´d}nd}|du rÎt	 
d¡ d}t  | ||||¡S )a  Given an :attr:`input` and a flow-field :attr:`grid`, computes the
    ``output`` using :attr:`input` values and pixel locations from :attr:`grid`.

    Currently, only spatial (4-D) and volumetric (5-D) :attr:`input` are
    supported.

    In the spatial (4-D) case, for :attr:`input` with shape
    :math:`(N, C, H_\text{in}, W_\text{in})` and :attr:`grid` with shape
    :math:`(N, H_\text{out}, W_\text{out}, 2)`, the output will have shape
    :math:`(N, C, H_\text{out}, W_\text{out})`.

    For each output location ``output[n, :, h, w]``, the size-2 vector
    ``grid[n, h, w]`` specifies :attr:`input` pixel locations ``x`` and ``y``,
    which are used to interpolate the output value ``output[n, :, h, w]``.
    In the case of 5D inputs, ``grid[n, d, h, w]`` specifies the
    ``x``, ``y``, ``z`` pixel locations for interpolating
    ``output[n, :, d, h, w]``. :attr:`mode` argument specifies ``nearest`` or
    ``bilinear`` interpolation method to sample the input pixels.

    :attr:`grid` specifies the sampling pixel locations normalized by the
    :attr:`input` spatial dimensions. Therefore, it should have most values in
    the range of ``[-1, 1]``. For example, values ``x = -1, y = -1`` is the
    left-top pixel of :attr:`input`, and values  ``x = 1, y = 1`` is the
    right-bottom pixel of :attr:`input`.

    If :attr:`grid` has values outside the range of ``[-1, 1]``, the corresponding
    outputs are handled as defined by :attr:`padding_mode`. Options are

        * ``padding_mode="zeros"``: use ``0`` for out-of-bound grid locations,
        * ``padding_mode="border"``: use border values for out-of-bound grid locations,
        * ``padding_mode="reflection"``: use values at locations reflected by
          the border for out-of-bound grid locations. For location far away
          from the border, it will keep being reflected until becoming in bound,
          e.g., (normalized) pixel location ``x = -3.5`` reflects by border ``-1``
          and becomes ``x' = 1.5``, then reflects by border ``1`` and becomes
          ``x'' = -0.5``.

    Note:
        This function is often used in conjunction with :func:`affine_grid`
        to build `Spatial Transformer Networks`_ .

    Note:
        When using the CUDA backend, this operation may induce nondeterministic
        behaviour in its backward pass that is not easily switched off.
        Please see the notes on :doc:`/notes/randomness` for background.

    Note:
        NaN values in :attr:`grid` would be interpreted as ``-1``.

    Args:
        input (Tensor): input of shape :math:`(N, C, H_\text{in}, W_\text{in})` (4-D case)
                        or :math:`(N, C, D_\text{in}, H_\text{in}, W_\text{in})` (5-D case)
        grid (Tensor): flow-field of shape :math:`(N, H_\text{out}, W_\text{out}, 2)` (4-D case)
                       or :math:`(N, D_\text{out}, H_\text{out}, W_\text{out}, 3)` (5-D case)
        mode (str): interpolation mode to calculate output values
            ``'bilinear'`` | ``'nearest'``. Default: ``'bilinear'``
            Note: When ``mode='bilinear'`` and the input is 5-D, the interpolation mode
            used internally will actually be trilinear. However, when the input is 4-D,
            the interpolation mode will legitimately be bilinear.
        padding_mode (str): padding mode for outside grid values
            ``'zeros'`` | ``'border'`` | ``'reflection'``. Default: ``'zeros'``
        align_corners (bool, optional): Geometrically, we consider the pixels of the
            input  as squares rather than points.
            If set to ``True``, the extrema (``-1`` and ``1``) are considered as referring
            to the center points of the input's corner pixels. If set to ``False``, they
            are instead considered as referring to the corner points of the input's corner
            pixels, making the sampling more resolution agnostic.
            This option parallels the ``align_corners`` option in
            :func:`interpolate`, and so whichever option is used here
            should also be used there to resize the input image before grid sampling.
            Default: ``False``

    Returns:
        output (Tensor): output Tensor

    .. _`Spatial Transformer Networks`:
        https://arxiv.org/abs/1506.02025

    .. warning::
        When ``align_corners = True``, the grid positions depend on the pixel
        size relative to the input image size, and so the locations sampled by
        :func:`grid_sample` will differ for the same input given at different
        resolutions (that is, after being upsampled or downsampled).
        The default behavior up to version 1.2.0 was ``align_corners = True``.
        Since then, the default behavior has been changed to ``align_corners = False``,
        in order to bring it in line with the default for :func:`interpolate`.
    c                 S   s   g | ]}t |ƒtu‘qS r.   rÚ   rÛ   r.   r.   r/   rÞ      rß   zgrid_sample.<locals>.<listcomp>)rõ   Úpadding_moderT  ræ   rQ  zWnn.functional.grid_sample(): expected mode to be 'bilinear' or 'nearest', but got: '{}'ri  rj  rk  zjnn.functional.grid_sample(): expected padding_mode to be 'zeros', 'border', or 'reflection', but got: '{}'r   r   r   NúÐDefault grid_sample and affine_grid behavior has changed to align_corners=False since 1.3.0. Please specify align_corners=True if the old behavior is desired. See the documentation of grid_sample for details.F)r   r   r    rá   r   r   Úgrid_sampler$   rR   rÁ   rÂ   Zgrid_sampler)r,   Zgridrõ   rl  rT  rä   r   Zpadding_mode_enumr.   r.   r/   rn  Å  s6    Y
þÿþ
rn  c                 C   sd  t j ¡ s4t| ƒtur4t| fƒr4tt| f| ||d�S |du rJt 	d¡ d}|  
¡ sbtd | j¡ƒ‚t|ƒdkr¶|  ¡ dks–| jd d	ks–| jd
 dkr¨td || j¡ƒ‚|dd… }ndt|ƒdk�r|  ¡ dksì| jd dksì| jd
 dkrþtd || j¡ƒ‚|dd… }ntd |¡ƒ‚|�r:t|ƒdk�r:t 	d¡ nt|ƒdk�rVtd |¡ƒ‚t  | ||¡S )a~	  Generates a 2D or 3D flow field (sampling grid), given a batch of
    affine matrices :attr:`theta`.

    .. note::
        This function is often used in conjunction with :func:`grid_sample`
        to build `Spatial Transformer Networks`_ .

    Args:
        theta (Tensor): input batch of affine matrices with shape
            (:math:`N \times 2 \times 3`) for 2D or
            (:math:`N \times 3 \times 4`) for 3D
        size (torch.Size): the target output image size.
            (:math:`N \times C \times H \times W` for 2D or
            :math:`N \times C \times D \times H \times W` for 3D)
            Example: torch.Size((32, 3, 24, 24))
        align_corners (bool, optional): if ``True``, consider ``-1`` and ``1``
            to refer to the centers of the corner pixels rather than the image corners.
            Refer to :func:`grid_sample` for a more complete description.
            A grid generated by :func:`affine_grid` should be passed to :func:`grid_sample`
            with the same setting for this option.
            Default: ``False``

    Returns:
        output (Tensor): output Tensor of size (:math:`N \times H \times W \times 2`)

    .. _`Spatial Transformer Networks`:
        https://arxiv.org/abs/1506.02025

    .. warning::
        When ``align_corners = True``, the grid positions depend on the pixel
        size relative to the input image size, and so the locations sampled by
        :func:`grid_sample` will differ for the same input given at different
        resolutions (that is, after being upsampled or downsampled).
        The default behavior up to version 1.2.0 was ``align_corners = True``.
        Since then, the default behavior has been changed to ``align_corners = False``,
        in order to bring it in line with the default for :func:`interpolate`.
    .. warning::
        When ``align_corners = True``, 2D affine transforms on 1D data and
        3D affine transforms on 2D data (that is, when one of the spatial
        dimensions has unit size) are ill-defined, and not an intended use case.
        This is not a problem when ``align_corners = False``.
        Up to version 1.2.0, all grid points along a unit dimension were
        considered arbitrarily to be at ``-1``.
        From version 1.3.0, under ``align_corners = True`` all grid points
        along a unit dimension are considered to be at ```0``
        (the center of the input image).
    )rT  Nrm  Fz6Expected theta to have floating point type, but got {}r3   r   éþÿÿÿr   r—   zJExpected a batch of 2D affine matrices of shape Nx2x3 for size {}. Got {}.rc  zJExpected a batch of 3D affine matrices of shape Nx3x4 for size {}. Got {}.éýÿÿÿzfaffine_grid only supports 4D and 5D sizes, for 2D and 3D affine transforms, respectively. Got size {}.r   zÅSince version 1.3.0, affine_grid behavior has changed for unit-size grids when align_corners=True. This is not an intended use case of affine_grid. See the documentation of affine_grid for details.r   z/Expected non-zero, positive output size. Got {})r   r   r    r!   r"   r   r   Úaffine_gridrÁ   rÂ   rû   r$   rR   r   rP   r˜   rü   rÿ   ÚminZaffine_grid_generator)Úthetar&   rT  Zspatial_sizer.   r.   r/   rq  B  sD    1
ÿ
ÿ(ÿ(ÿþÿrq  Úconstantc                 C   sè  t j ¡ s6t| ƒtur6t| fƒr6tt| f| |||d�S t|ƒd dksNJ dƒ‚t|ƒd |  	¡ ksjJ dƒ‚|dkr€t
 | ||¡S |dks–J d |¡ƒ‚|  	¡ dk�rt|ƒdks¸J d	ƒ‚|d
krÐt jj | |¡S |dkrèt jj | |¡S |dk� rüt| |ƒS t‚nâ|  	¡ dk�rtt|ƒdk�s&J dƒ‚|d
k�r@t jj | |¡S |dk�rZt jj | |¡S |dk�rnt| |ƒS t‚np|  	¡ dk�rÜt|ƒdk�s˜J dƒ‚|d
k�r¨t‚n2|dk�rÂt jj | |¡S |dk�rÖt| |ƒS t‚ntdƒ‚dS )aÝ
  Pads tensor.

    Padding size:
        The padding size by which to pad some dimensions of :attr:`input`
        are described starting from the last dimension and moving forward.
        :math:`\left\lfloor\frac{\text{len(pad)}}{2}\right\rfloor` dimensions
        of ``input`` will be padded.
        For example, to pad only the last dimension of the input tensor, then
        :attr:`pad` has the form
        :math:`(\text{padding\_left}, \text{padding\_right})`;
        to pad the last 2 dimensions of the input tensor, then use
        :math:`(\text{padding\_left}, \text{padding\_right},`
        :math:`\text{padding\_top}, \text{padding\_bottom})`;
        to pad the last 3 dimensions, use
        :math:`(\text{padding\_left}, \text{padding\_right},`
        :math:`\text{padding\_top}, \text{padding\_bottom}`
        :math:`\text{padding\_front}, \text{padding\_back})`.

    Padding mode:
        See :class:`torch.nn.ConstantPad2d`, :class:`torch.nn.ReflectionPad2d`, and
        :class:`torch.nn.ReplicationPad2d` for concrete examples on how each of the
        padding modes works. Constant padding is implemented for arbitrary dimensions.
        Replicate padding is implemented for padding the last 3 dimensions of 5D input
        tensor, or the last 2 dimensions of 4D input tensor, or the last dimension of
        3D input tensor. Reflect padding is only implemented for padding the last 2
        dimensions of 4D input tensor, or the last dimension of 3D input tensor.

    Note:
        When using the CUDA backend, this operation may induce nondeterministic
        behaviour in its backward pass that is not easily switched off.
        Please see the notes on :doc:`/notes/randomness` for background.

    Args:
        input (Tensor): N-dimensional tensor
        pad (tuple): m-elements tuple, where
            :math:`\frac{m}{2} \leq` input dimensions and :math:`m` is even.
        mode: ``'constant'``, ``'reflect'``, ``'replicate'`` or ``'circular'``.
            Default: ``'constant'``
        value: fill value for ``'constant'`` padding. Default: ``0``

    Examples::

        >>> t4d = torch.empty(3, 3, 4, 2)
        >>> p1d = (1, 1) # pad last dim by 1 on each side
        >>> out = F.pad(t4d, p1d, "constant", 0)  # effectively zero padding
        >>> print(out.size())
        torch.Size([3, 3, 4, 4])
        >>> p2d = (1, 1, 2, 2) # pad last dim by (1, 1) and 2nd to last by (2, 2)
        >>> out = F.pad(t4d, p2d, "constant", 0)
        >>> print(out.size())
        torch.Size([3, 3, 8, 4])
        >>> t4d = torch.empty(3, 3, 4, 2)
        >>> p3d = (0, 1, 2, 1, 3, 3) # pad by (0, 1), (2, 1), and (3, 3)
        >>> out = F.pad(t4d, p3d, "constant", 0)
        >>> print(out.size())
        torch.Size([3, 9, 7, 3])

    )rõ   r’   r   r   z%Padding length must be divisible by 2zPadding length too largert  z1Padding mode "{}"" doesn't take in value argumentr   z&3D tensors expect 2 values for paddingZreflectZ	replicateZcircularr3   z&4D tensors expect 4 values for paddingrc  rH   z&5D tensors expect 6 values for paddingzGOnly 3D, 4D, 5D padding with non-constant padding are supported for nowN)r   r   r    r!   r"   r   r   Ú_padrP   r˜   r   Zconstant_pad_ndrR   r(   r)   Zreflection_pad1dZreplication_pad1dÚ_pad_circularrÿ   Zreflection_pad2dZreplication_pad2dZreplication_pad3d)r,   r  rõ   r’   r.   r.   r/   ru  ž  sL    <
ÿ









ru  ç�íµ ÷Æ°>c                 C   s   t  | ||||¡S )z<
    See :class:`torch.nn.PairwiseDistance` for details
    )r   Úpairwise_distance)Úx1Zx2r�   rÏ   rÑ   r.   r.   r/   rx    s    rx  a„  
pdist(input, p=2) -> Tensor

Computes the p-norm distance between every pair of row vectors in the input.
This is identical to the upper triangular portion, excluding the diagonal, of
`torch.norm(input[:, None] - input, dim=2, p=p)`. This function will be faster
if the rows are contiguous.

If input has shape :math:`N \times M` then the output will have shape
:math:`\frac{1}{2} N (N - 1)`.

This function is equivalent to `scipy.spatial.distance.pdist(input,
'minkowski', p=p)` if :math:`p \in (0, \infty)`. When :math:`p = 0` it is
equivalent to `scipy.spatial.distance.pdist(input, 'hamming') * M`.
When :math:`p = \infty`, the closest scipy function is
`scipy.spatial.distance.pdist(xn, lambda x, y: np.abs(x - y).max())`.

Args:
    input: input tensor of shape :math:`N \times M`.
    p: p value for the p-norm distance to calculate between each vector pair
        :math:`\in [0, \infty]`.
a  
cosine_similarity(x1, x2, dim=1, eps=1e-8) -> Tensor

Returns cosine similarity between x1 and x2, computed along dim.

.. math ::
    \text{similarity} = \dfrac{x_1 \cdot x_2}{\max(\Vert x_1 \Vert _2 \cdot \Vert x_2 \Vert _2, \epsilon)}

Args:
    x1 (Tensor): First input.
    x2 (Tensor): Second input (of size matching x1).
    dim (int, optional): Dimension of vectors. Default: 1
    eps (float, optional): Small value to avoid division by zero.
        Default: 1e-8

Shape:
    - Input: :math:`(\ast_1, D, \ast_2)` where D is at position `dim`.
    - Output: :math:`(\ast_1, \ast_2)` where 1 is at position `dim`.

Example::

    >>> input1 = torch.randn(100, 128)
    >>> input2 = torch.randn(100, 128)
    >>> output = F.cosine_similarity(input1, input2)
    >>> print(output)
aa  
one_hot(tensor, num_classes=-1) -> LongTensor

Takes LongTensor with index values of shape ``(*)`` and returns a tensor
of shape ``(*, num_classes)`` that have zeros everywhere except where the
index of last dimension matches the corresponding value of the input tensor,
in which case it will be 1.

See also `One-hot on Wikipedia`_ .

.. _One-hot on Wikipedia:
    https://en.wikipedia.org/wiki/One-hot

Arguments:
    tensor (LongTensor): class values of any shape.
    num_classes (int):  Total number of classes. If set to -1, the number
        of classes will be inferred as one greater than the largest class
        value in the input tensor.

Returns:
    LongTensor that has one more dimension with 1 values at the
    index of last dimension indicated by the input, and 0 everywhere
    else.

Examples:
    >>> F.one_hot(torch.arange(0, 5) % 3)
    tensor([[1, 0, 0],
            [0, 1, 0],
            [0, 0, 1],
            [1, 0, 0],
            [0, 1, 0]])
    >>> F.one_hot(torch.arange(0, 5) % 3, num_classes=5)
    tensor([[1, 0, 0, 0, 0],
            [0, 1, 0, 0, 0],
            [0, 0, 1, 0, 0],
            [1, 0, 0, 0, 0],
            [0, 1, 0, 0, 0]])
    >>> F.one_hot(torch.arange(0, 6).view(3,2) % 3)
    tensor([[[1, 0, 0],
             [0, 1, 0]],
            [[0, 0, 1],
             [1, 0, 0]],
            [[0, 1, 0],
             [0, 0, 1]]])
c
                 C   sŽ   t j ¡ sN| ||f}
tdd„ |
D ƒƒrNt|
ƒrNtt|
| |||||||||	d�S |dus^|durlt ||¡}n
t 	|	¡}t  | |||||||¡S )z>
    See :class:`~torch.nn.TripletMarginLoss` for details
    c                 S   s   g | ]}t |ƒtu‘qS r.   rÚ   rÛ   r.   r.   r/   rÞ   ‚  rß   z'triplet_margin_loss.<locals>.<listcomp>)rF  r�   rÏ   Úswapr$  r&  r!  N)
r   r   r    rá   r   r   Útriplet_margin_lossr  r5  r  )ÚanchorÚpositiveÚnegativerF  r�   rÏ   rz  r$  r&  r!  rä   r-  r.   r.   r/   r{  z  s    


ý
ÿr{  ©Údistance_functionrF  rz  r!  c                C   sÖ   t j ¡ rtdƒ‚| ||f}tdd„ |D ƒƒrPt|ƒrPtt|| ||||||d�	S |dur\|nt}|| |ƒ}|| |ƒ}	|rŽ|||ƒ}
t  	|	|
¡}	t j
||	 | dd�}t |¡}|dkr¾| ¡ S |d	krÎ| ¡ S |S dS )
zK
    See :class:`~torch.nn.TripletMarginWithDistanceLoss` for details.
    zuF.triplet_margin_with_distance_loss does not support JIT scripting: functions requiring Callables cannot be scripted.c                 S   s   g | ]}t |ƒtu‘qS r.   rÚ   rÛ   r.   r.   r/   rÞ   š  rß   z5triplet_margin_with_distance_loss.<locals>.<listcomp>r  Nr„   )rr  r   r   )r   r   r    rÿ   rá   r   r   Ú!triplet_margin_with_distance_lossrx  rr  Úclampr  r  ró   rø   )r|  r}  r~  r€  rF  rz  r!  rä   Zpositive_distZnegative_distZ	swap_distrå   r-  r.   r.   r/   r�  �  s*    


þ



r�  çê-�™—q=c              	   C   s”   t j ¡ s8t| ƒtur8t| fƒr8tt| f| ||||d�S |du rd| j||dd� 	|¡ 
| ¡}| | S | j||dd� |¡ 
| ¡}t j| ||d�S dS )aL  Performs :math:`L_p` normalization of inputs over specified dimension.

    For a tensor :attr:`input` of sizes :math:`(n_0, ..., n_{dim}, ..., n_k)`, each
    :math:`n_{dim}` -element vector :math:`v` along dimension :attr:`dim` is transformed as

    .. math::
        v = \frac{v}{\max(\lVert v \rVert_p, \epsilon)}.

    With the default arguments it uses the Euclidean norm over vectors along dimension :math:`1` for normalization.

    Args:
        input: input tensor of any shape
        p (float): the exponent value in the norm formulation. Default: 2
        dim (int): the dimension to reduce. Default: 1
        eps (float): small value to avoid division by zero. Default: 1e-12
        out (Tensor, optional): the output tensor. If :attr:`out` is used, this
                                operation won't be differentiable.
    )r�   r˜   rÏ   rm   NTrÐ   )rm   )r   r   r    r!   r"   r   r   Ú	normalizeZnormZ	clamp_minZ	expand_asZ
clamp_min_r  )r,   r�   r˜   rÏ   rm   Zdenomr.   r.   r/   r„  ³  s    
ÿr„  c                 C   s(   t | tƒs$t| ƒdks$J | |¡ƒ‚d S )Nr   )rY   r%   rP   rR   )Úargr4   Úmessager.   r.   r/   Úassert_int_or_pairÓ  s    r‡  c              	   C   s´   t j ¡ s8t| ƒtur8t| fƒr8tt| f| ||||d�S |  ¡ dkržd}t	|d|ƒ t	|d|ƒ t	|d|ƒ t	|d|ƒ t j
j | t|ƒt|ƒt|ƒt|ƒ¡S td |  ¡ ¡ƒ‚d	S )
a
  Extracts sliding local blocks from an batched input tensor.

    .. warning::
        Currently, only 4-D input tensors (batched image-like tensors) are
        supported.

    .. warning::

        More than one element of the unfolded tensor may refer to a single
        memory location. As a result, in-place operations (especially ones that
        are vectorized) may result in incorrect behavior. If you need to write
        to the tensor, please clone it first.


    See :class:`torch.nn.Unfold` for details
    ©r@   r?   r>   r3   z&{} must be int or 2-tuple for 4D inputr-   r@   r?   r>   z:Input Error: Only 4D input Tensors are supported (got {}D)N)r   r   r    r!   r"   r   r   Úunfoldr˜   r‡  r(   r)   Zim2colr   rÿ   rR   )r,   r-   r@   r?   r>   Úmsgr.   r.   r/   r‰  Ø  s     
þÿr‰  c              
   C   sÈ   t j ¡ s:t| ƒtur:t| fƒr:tt| f| |||||d�S |  ¡ dkr²d}t	|d|ƒ t	|d|ƒ t	|d|ƒ t	|d|ƒ t	|d|ƒ t j
j | t|ƒt|ƒt|ƒt|ƒt|ƒ¡S td	 |  ¡ ¡ƒ‚d
S )zøCombines an array of sliding local blocks into a large containing
    tensor.

    .. warning::
        Currently, only 3-D output tensors (unfolded batched image-like tensors) are
        supported.

    See :class:`torch.nn.Fold` for details
    rˆ  r   z&{} must be int or 2-tuple for 3D inputr   r-   r@   r?   r>   z:Input Error: Only 3D input Tensors are supported (got {}D)N)r   r   r    r!   r"   r   r   Úfoldr˜   r‡  r(   r)   Zcol2imr   rÿ   rR   )r,   r   r-   r@   r?   r>   rŠ  r.   r.   r/   r‹  ü  s"    
þÿr‹  c                 C   s¶  | j }|dd… }t|ƒ}t|ƒD ]x\}}||d d   |ksHJ dƒ‚||d d   |ksfJ dƒ‚||d d   ||d d    | dks"J dƒ‚q"|dd… }t|ƒD ]6\}}||||d d    ||d d    f7 }q°tj|| j| j| jd�}|dk�rvt|d dƒ}	|d t|d	 dƒ }
t|d  dƒ}|d t|d	  dƒ }| d
||…f |d
|	|
…f< �nð|dk�rDt|d dƒ}	|d t|d	 dƒ }
t|d dƒ}|d t|d dƒ }t|d  dƒ}|d t|d	  dƒ }t|d  dƒ}|d t|d  dƒ }| d
||…||…f |d
|	|
…||…f< �n"|dk�rft|d dƒ}	|d t|d	 dƒ }
t|d dƒ}|d t|d dƒ }t|d dƒ}|d t|d dƒ }t|d  dƒ}|d t|d	  dƒ }t|d  dƒ}|d t|d  dƒ }t|d  dƒ}|d t|d  dƒ }| d
||…||…||…f |d
|	|
…||…||…f< |d dk�rä|d |d  t|d	 dƒ }|d t|d	 dƒ }d}|d }|dd…dd…||…f |dd…dd…||…f< |d	 dk�r^t|d dƒ}t|d dƒ|d	  }|d |d	  }|d }|dd…dd…||…f |dd…dd…||…f< t|ƒdk�r||d dk�rö|d |d  t|d dƒ }|d t|d dƒ }d}|d }|dd…dd…dd…||…f |dd…dd…dd…||…f< |d dk�r|t|d dƒ}t|d dƒ|d  }|d |d  }|d }|dd…dd…dd…||…f |dd…dd…dd…||…f< t|ƒdk�r²|d dk�r |d |d  t|d dƒ }|d t|d dƒ }d}|d }|dd…dd…dd…dd…||…f |dd…dd…dd…dd…||…f< |d dk�r²t|d dƒ}t|d dƒ|d  }|d |d  }|d }|dd…dd…dd…dd…||…f |dd…dd…dd…dd…||…f< |S )a„  Circularly pads tensor.

    Tensor values at the beginning are used to pad the end, and values at the
    end are used to pad the beginning. For example, consider a single dimension
    with values [0, 1, 2, 3]. With circular padding of (1, 1) it would be
    padded to [3, 0, 1, 2, 3, 0], and with padding (1, 2) it would be padded to
    [3, 0, 1, 2, 3, 0, 1]. If negative padding is applied then the ends of the
    tensor get removed. With circular padding of (-1, -1) the previous example
    would become [1, 2]. Circular padding of (-1, 1) would produce
    [1, 2, 3, 1].

    The first and second dimensions of the tensor are not padded.

    Args:
        input: Tensor with shape :math:`(N, C, D[, H, W])`.
        padding: Tuple containing the number of elements to pad each side of
            the tensor. The length of padding must be twice the number of
            paddable dimensions. For example, the length of padding should be 4
            for a tensor of shape :math:`(N, C, H, W)`, and the length should
            be 6 for a tensor of shape :math:`(N, C, D, H, W)`.

    Examples::

        >>> x = torch.tensor([[[[0, 1, 2], [3, 4, 5]]]])  # Create tensor
        >>> # Example 1
        >>> padding = (1, 1, 1, 1)
        >>> y = F.pad(x, padding, mode='circular')
        >>> print(y)
        tensor([[[[5, 3, 4, 5, 3],
                  [2, 0, 1, 2, 0],
                  [5, 3, 4, 5, 3],
                  [2, 0, 1, 2, 0]]]])
        >>> print(y.shape)
        torch.Size([1, 1, 4, 5])
        >>> # Example 2
        >>> padding = (1, 1, 2, 2)
        >>> z = F.pad(x, padding, mode='circular')
        >>> print(z)
        tensor([[[[2, 0, 1, 2, 0],
                  [5, 3, 4, 5, 3],
                  [2, 0, 1, 2, 0],
                  [5, 3, 4, 5, 3],
                  [2, 0, 1, 2, 0],
                  [5, 3, 4, 5, 3]]]])
        >>> print(z.shape)
        torch.Size([1, 1, 6, 5])
    r   Nr   z4Padding value causes wrapping around more than once.r   z:Negative padding value is resulting in an empty dimension.)r   Úlayoutr   ro  r—   .éüÿÿÿr   rp  iúÿÿÿr3   éûÿÿÿ)	rü   rP   Ú	enumerater   Úemptyr   rŒ  r   rÔ   )r,   r?   Zin_shapeZpaddable_shaperÄ   Úidxr&   Z	out_shaperm   Zout_d0Zout_d1Zin_d0Zin_d1Zout_h0Zout_h1Zin_h0Zin_h1Zout_w0Zout_w1Zin_w0Zin_w1Zi0Úi1Zo0Zo1r.   r.   r/   rv    s¼    1ÿÿ.ÿ0ÿ
 
ÿ
ÿ00ÿÿ$ÿ$$ÿ$rv  )ÚqueryÚkeyr’   Úembed_dim_to_checkÚ	num_headsÚin_proj_weightÚin_proj_biasÚbias_kÚbias_vÚadd_zero_attnÚ	dropout_pÚout_proj_weightÚout_proj_biasr‚   Úkey_padding_maskÚneed_weightsÚ	attn_maskÚuse_separate_proj_weightÚq_proj_weightÚk_proj_weightÚv_proj_weightÚstatic_kÚstatic_vr”   c           ,      C   s	  t j ¡ st| ||||||||f	}tdd„ |D ƒƒrtt|ƒrttt|| |||||||||	|
||||||||||||d�S |  ¡ \}}}||ksŽJ ‚| d¡| d¡kr¶| d¡| d¡ksºJ ‚|| }|| |ksÖJ dƒ‚t|ƒd }|�sºt  	| |¡�r$t  	||¡�r$t
| ||ƒjdd	d
�\}}}�qÐt  	||¡�rè|} d}!|}"||!|"…dd…f }#| du�rh| |!|"… } t
| |#| ƒ}|du �r–|du �sŒJ ‚d}d}nP|} |}!d}"||!d…dd…f }#| du�rÌ| |!d… } t
||#| ƒjdd	d
�\}}nÎ|} d}!|}"||!|"…dd…f }#| du�r| |!|"… } t
| |#| ƒ}|} |}!|d }"||!|"…dd…f }#| du�rd| |!|"… } t
||#| ƒ}|} |d }!d}"||!d…dd…f }#| du�rª| |!d… } t
||#| ƒ}�nt j |¡}$|$ ¡ \}%}&|%|k�rì|&|  d	¡k�sðJ ‚t j |¡}'|' ¡ \}%}&|%|k�r"|&| d	¡k�s&J ‚t j |¡}(|( ¡ \}%}&|%|k�rX|&| d	¡k�s\J ‚|du�r¬t
| |$|d|… ƒ}t
||'|||d … ƒ}t
||(||d d… ƒ}n$t
| |$|ƒ}t
||'|ƒ}t
||(|ƒ}|| }|du�rô|jt jk�s8|jt jk�s8|jt jk�s8|jt jk�s8|jt jk�s8J d |j¡ƒ‚|jt jk�r\t d¡ | t j¡}| ¡ dk�r¢| d¡}t| ¡ ƒd|  d¡| d¡gk�rôtdƒ‚nR| ¡ dk�rât| ¡ ƒ|| |  d¡| d¡gk�rôtdƒ‚ntd | ¡ ¡ƒ‚|du�r"|jt jk�r"t d¡ | t j¡}|du�rÊ|du�rÊ|du �r¤|du �r¤t  || d|d¡g¡}t  || d|d¡g¡}|du�rŽt|dƒ}|du�rÈt|dƒ}n$|du �s¶J dƒ‚|du �sæJ dƒ‚n|du �sØJ ‚|du �sæJ ‚| ¡  ||| |¡  dd¡}|du�r,| ¡  d	|| |¡  dd¡}|du�rT| ¡  d	|| |¡  dd¡}|du�rŽ| d¡|| k�svJ ‚| d¡|k�sŠJ ‚|}|du�rÈ| d¡|| k�s°J ‚| d¡|k�sÄJ ‚|}| d¡})|du�r| d¡|k�sðJ ‚| d¡|)k�sJ ‚|	�r²|)d7 })t j|t j!| d¡df| ¡ dd…  |j|j"d�gdd
�}t j|t j!| d¡df| ¡ dd…  |j|j"d�gdd
�}|du�ržt|dƒ}|du�r²t|dƒ}t  #||  dd¡¡}*t|* ¡ ƒ|| ||)gk�sæJ ‚|du�r|jt jk�r|* $|tdƒ¡ n|*|7 }*|du�r`|* ||||)¡}*|* %| d¡ d¡tdƒ¡}*|* || ||)¡}*t&|*d	d
�}*t'|*|
|d�}*t  #|*|¡}+t|+ ¡ ƒ|| ||gk�s¦J ‚|+  dd¡ ¡  |||¡}+t
|+||ƒ}+|�rö|* ||||)¡}*|+|*j(dd
�| fS |+dfS dS )a?  
    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.
        embed_dim_to_check: total dimension of the model.
        num_heads: parallel attention heads.
        in_proj_weight, in_proj_bias: input projection weight and bias.
        bias_k, bias_v: bias of the key and value sequences to be added at dim=0.
        add_zero_attn: add a new batch of zeros to the key and
                       value sequences at dim=1.
        dropout_p: probability of an element to be zeroed.
        out_proj_weight, out_proj_bias: the output projection weight and bias.
        training: apply dropout if is ``True``.
        key_padding_mask: if provided, specified padding elements in the key will
            be ignored by the attention. This is an binary mask. When the value is True,
            the corresponding value on the attention layer will be filled with -inf.
        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.
        use_separate_proj_weight: the function accept the proj. weights for query, key,
            and value in different forms. If false, in_proj_weight will be used, which is
            a combination of q_proj_weight, k_proj_weight, v_proj_weight.
        q_proj_weight, k_proj_weight, v_proj_weight, in_proj_bias: input projection weight and bias.
        static_k, static_v: static key and value used for attention operators.


    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 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 ensures 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``
          are not allowed to attend while ``False`` values will be unchanged. If a FloatTensor
          is provided, it will be added to the attention weight.
        - static_k: :math:`(N*num_heads, S, E/num_heads)`, where S is the source sequence length,
          N is the batch size, E is the embedding dimension. E/num_heads is the head dimension.
        - static_v: :math:`(N*num_heads, S, E/num_heads)`, where S is the source sequence length,
          N is the batch size, E is the embedding dimension. E/num_heads is the head dimension.

        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.
    c                 S   s   g | ]}t |ƒtu‘qS r.   rÚ   rÛ   r.   r.   r/   rÞ     rß   z0multi_head_attention_forward.<locals>.<listcomp>)
r‚   rŸ  r   r¡  r¢  r£  r¤  r¥  r¦  r§  r   r   z(embed_dim must be divisible by num_headsg      à¿r   r—   r™   Nr   zDOnly float, byte, and bool types are supported for attn_mask, not {}zZByte tensor for attn_mask in nn.MultiheadAttention is deprecated. Use bool tensor instead.z,The size of the 2D attn_mask is not correct.z,The size of the 3D attn_mask is not correct.z)attn_mask's dimension {} is not supportedzaByte tensor for key_padding_mask in nn.MultiheadAttention is deprecated. Use bool tensor instead.)r   r   z#bias cannot be added to static key.z%bias cannot be added to static value.r   z-inf)r�   r‚   ))r   r   r    rá   r   r   Úmulti_head_attention_forwardr&   r]  Úequalrâ   ÚchunkZ_unwrap_optionalr   r^  Úfloat64Úfloat16Zuint8ÚboolrR   rÁ   rÂ   Útor˜   r\   rZ   r›   ÚcatÚrepeatr  rï   r  Z	transposeri  r   ZbmmZmasked_fill_Zmasked_fillrÊ   r†   rø   ),r“  r”  r’   r•  r–  r—  r˜  r™  rš  r›  rœ  r�  rž  r‚   rŸ  r   r¡  r¢  r£  r¤  r¥  r¦  r§  rä   Ztgt_lenZbszZ	embed_dimZhead_dimZscalingÚqr  ÚvÚ_bÚ_startZ_endÚ_wZq_proj_weight_non_optZlen1Zlen2Zk_proj_weight_non_optZv_proj_weight_non_optZsrc_lenZattn_output_weightsZattn_outputr.   r.   r/   r¨  É  sN   P
ÿ

ø	, 








ÿ
ÿ
ÿ
þ

$
(










<<



 

þÿ r¨  )NNFN)NNFN)NNFN)NNFN)Nr   r   FF)Nr   r   FF)Nr   r   FF)Nr   r   FF)Nr   r   FF)Nr   r   FF)Nr   N)Nr   N)Nr   N)NF)NF)F)F)F)F)F)F)r   TF)r   FF)r   TF)r   TF)r   FF)F)F)r—   )rœ   rc   F)F)rc   F)F)rc   F)r¬   F)r²   r³   FF)r   )Nr   N)Nr   N)r   FrÌ   r—   )Nr   N)F)N)N)F)F)NNrî   FF)NNr   Fró   FNF)NNFr  r  )NNNNTr  r  )NNr  )NNr  )r  r  rc   )r   ró   F)NNr"  Nró   )TFNr.  Nró   )NNró   F)NNr"  Nró   )NNNró   )NNNró   N)NNró   rc   )NNró   )NNró   )r   NNró   )rc   NNró   )NNró   )NNró   )NNNró   )r   NNró   )r   rc   NNNró   )NNrQ  N)NNrQ  N)NNrQ  N)NNrQ  NN)NNrQ  NN)NNrQ  NN)NNrQ  NN)NNrQ  NN)NN)NN)NN)NN)NN)NN)NN)NN)ræ   ri  N)N)rt  r   )rî   rw  F)rc   r   rw  FNNró   )r   r   rƒ  N)r   r   r   )r   r   r   )
TNTNFNNNNN)­Ú__doc__rÁ   rb  r   Ztorch._Cr   r   Ú r   r  Úmodulesr   Zmodules.utilsr   r   r	   r
   r   r   Z_jit_internalr   r   r   r   r   Z	overridesr   r   r"   Zconv1dZconv2dZconv3dZconv_transpose1dZconv_transpose2dZconv_transpose3dZconv_tbcro   r(   r)   re   r  r#   r2   Ú__name__r*   r:   r<   r;   rB   rG   rF   rI   rK   rJ   rL   rN   rM   rV   rX   r[   r`   rd   rn   rq   ru   rr   rv   rx   rw   ry   r{   rz   re  r|   r~   r†   rˆ   r‰   rŒ   r�   r�   r‘   r�   r­  rh   r•   r%   rš   r]  rŸ   r    r¡   r¥   r¦   r¨   r©   rª   r«   r®   r¯   r°   r¶   r·   Zlog_sigmoidrN  r¸   r»   r¼   r¾   ZsoftplusrÅ   rÈ   rÊ   rÒ   r×   Z
softshrinkr½   rØ   rÙ   râ   ræ   ré   rê   rí   rð   rù   r  r  r  r  r  r  r  r(  r2  r4  r6  r8  r;  r=  rB  rD  rG  rI  rJ  rL  rM  rO  rP  Zpixel_shuffleZchannel_shufflerU  rW  rg  rh  ZGRID_SAMPLE_INTERPOLATION_MODESZGRID_SAMPLE_PADDING_MODESrn  rq  ru  r  rx  ZpdistZcosine_similarityZone_hotr{  r�  r„  r‡  r‰  r‹  rv  r¨  r.   r.   r.   r/   Ú<module>   s°  &(&)+*  þ
5  þ
ù
  þ
7  þ
ù
 ÿ
 ÿ
ù
 ÿ
 ÿ
ù
 ÿ
 ÿ
ù
 ÿ
 ÿ
 ÿ
	ù
	ù
	ù
"'?	 ÿ
Q  þ
 ( ÿ
 ÿ
  ÿ
9 ÿ
] ÿ
3D ÿ
7 ÿ
: ÿ
8 ÿ
 ÿ
 ÿ
# ÿ
 ÿ
%> Jþý}\l/ ÿÿ$ $ =         êé