o
    h                 8   @   sz  d Z ddlZddlZddlZddlmZmZmZmZ ddl	Z	ddl	m
Z
mZmZ ddlmZmZ ddlmZmZmZmZmZ ddlmZmZmZ ddlmZmZ dd	lm Z m!Z!m"Z"m#Z# dd
l$m%Z%m&Z&m'Z'm(Z( erqddl)m*Z+ ne,Z+zddl-Z.W n e/y   dZ.Y nw ee	j0dj1di eed Z0ee	j2dj1di eed Z2ee	j3dj1di eed Z3ee	j4dj1di eed Z4ee	j5dj1di eed Z5ee	j6dj1di eed Z6ee	j7dZ7ee	j8dZ8ee	j9j:j;dZ;ee	j9j:j<dZ<				ddedee, deee,  d eee=  d!e>d"ee d#e?eef fd$d%Z@				ddedee, deee,  d eee=  d!e>d"ee d#efd&d'ZAed!d(de@eAeBd)d*ZC				ddedee, deee,  d eee=  d!e>d"ee d#e?eef fd+d,ZD				ddedee, deee,  d eee=  d!e>d"ee d#efd-d.ZEed!d(deDeEeBd/d*ZF			0		ddedee, d1eee,  d2ee, d3ee, d4e>d!e>d#e?eef fd5d6ZG			0		ddedee, d1eee,  d2ee, d3ee, d4e>d!e>d#efd7d8ZHed!d9deGeHeBd:d*ZI			0		ddedee, d1eee,  d2ee, d3ee, d4e>d!e>d#e?eef fd;d<ZJ			0		ddedee, d1eee,  d2ee, d3ee, d4e>d!e>d#efd=d>ZKed!d9deJeKeBd?d*ZL			0		ddedee, d1eee,  d2ee, d3ee, d4e>d!e>d#e?eef fd@dAZM			0		ddedee, d1eee,  d2ee, d3ee, d4e>d!e>d#efdBdCZNed!d9deMeNeBdDd*ZOdedePe, d1ePe, d2ePe, deePe,  d#ePe, fdEdFZQ			ddedGedee, d1eee,  d2ee, deee,  d#efdHdIZR			ddedGedee, d1eee,  d2ee, deee,  d#efdJdKZS			ddedGedee, d1eee,  d2ee, deee,  d#efdLdMZT		ddedNee,e=f dee, d1eee,  d4e>d#efdOdPZU		ddedNee,e=f dee, d1eee,  d4e>d#efdQdRZV		ddedNee,e=f de,d1eee,  d4e>d#efdSdTZW	ddedee, d!e>d#e?eef fdUdVZX	ddedee, d!e>d#efdWdXZYed!dYdeXeYeBdZd*ZZ	ddedee, d!e>d#e?eef fd[d\Z[	ddedee, d!e>d#efd]d^Z\ed!dYde[e\eBd_d*Z]	ddedee, d!e>d#e?eef fd`daZ^	ddedee, d!e>d#efdbdcZ_ed!dYde^e_eBddd*Z`ee	jadeZadedee, d#efdfdgZbdedee, d#efdhdiZc	j	k	ddedle=dme>dne>d#ef
dodpZd	j		ddedle=dme>dne>d#ef
dqdrZe	j	k	ddedle=dme>dne>d#ef
dsdtZf	j	k	ddedle=dme>dne>d#ef
dudvZg	j	k	ddedle=dme>dne>d#ef
dwdxZh	j		ddedle=dme>dne>d#ef
dydzZi	dded{e=d|e=dne>d#ef
d}d~ZjejZkee
jldZlddedne>d#efddZmee	jndZnddede,d#efddZo			ddede=de=dne>d#ef
ddZpee	j9j:jqdZqddedne>d#efddZrddede=dne>d#efddZsee	j9j:jtdZtddedne>d#efddZuee	jvdZv		ddede=dne>d#efddZwee	jxdZx		ddede=dne>d#efddZyee	j9j:jzdZzee	j{dZ{				ddede=de=dme>dne>d#efddZ|ee	j}dZ}ee	j9j:j~dZee	j9j:jdZee	jdZdd Zdd Zee	j9j:jdZdede,de,d#e,fddZ			ddedee, de,dee+ d#ef
ddZ			ddedee, de,dee+ d#ef
ddZ	0			ddede=de>de=de,d#efddZ			ddedee, de,dee+ d#ef
ddÄZee	j9j:jdăZddƄ ZddȄ Zddedne>d#efddʄZee	j9j:jdj1di eZee	jd̃Zddedne>d#efdd΄Zddedne>d#efddЄZddedne>d#efdd҄Zdedede=dNe=d#e?eef f
ddքZ					ddededee, dee= dNe=de>de>d#efdd܄Z			Y						ddededee dee= dNe=de>dede>dee de>dee, d#efddZej rej j1di ee_ dePe, d#dfddZ					ddedee dee dee dee dme>de=de=d#efddZdePe, d#dfddZ					k		ddedee dee dee dee de>de=de=d#efddZ			ddedePe, dee dee de=d#efddZ		ddedePe, dee dee= d#ef
ddZ			ddede,dee dee de=d#efddZ			ddede,de=de=de=d#efd dZ			dِdedededede,dede>d#efd	d
Zej rej j1di ee_ 					ݐddededee dee> de,dee> ded#efddZ	k					ݐddedede>de>dee> de=dee> ded#efddZ			ݐddededeee=f de>de=ded#efddZ				ddededee> dee> dede>d#efddZ					ݐ	ddededee dee> de,dee> dede=d#efd d!Z				ݐddededee dee> dee> ded#efd"d#Z					ddededee dee> dee> ded$ee d#efd%d&Z				ddededee> dee> dede=d#efd'd(Z			ddededed)e=dee d#efd*d+Z				ddededee> dee> dedee d#efd,d-Z				ddededee> dee> dedee d#efd.d/Z				ݐdd0ed1eded2e=dee> dee> ded#efd3d4Z				ݐddeded2e=dee> dee> ded#efd5d6Z			ݐddededee> dee> ded#efd7d8Z			ݐddededee> dee> ded#efd9d:Z				ݐddededee dee> dee> ded#efd;d<Z				ݐdd0ed1eded2e=dee> dee> ded#efd=d>Z	0					ݐddededle,d2e=dee dee> dee> ded#efd?d@Zee	jdAZee	jdBZee	jdCZee	jdDZe			E	ddedee, dFee= dedGee> d#efdHdIZe			E	ddedeePe,  dFee= dedGee> d#efdJdIZ			E	ddKdIZej rFej j1di ee_ d#e>fdLdMZe			E			ddedee, dFeePe=  dedGee> dNee> dOe>d#efdPdQZe			E			ddedeePe,  dFeePe=  dedGee> dNee> dOe>d#efdRdQZe			E			ddedee, dFee= dedGee> dNee> dOe>d#efdSdQZe			E			ddedeePe,  dFee= dedGee> dNee> dOe>d#efdTdQZ			E			ddedee, dFeePe=  dedGee> dNee> dOe>d#efdUdQZej rLej j1di ee_ e		ddedee, dFee= d#efdVdWZe		ddedeePe,  dFee= d#efdXdWZdאdYdWZej rej j1di ee_ e		ddedee, dFee= d#efdZd[Ze		ddedeePe,  dFee= d#efd\d[Ze		ddedee, dFeePe=  d#efd]d[Ze		ddedeePe,  dFeePe=  d#efd^d[Zdאd_d[Zej r ej j1di ee_ dd0dYd`Zdd0dYdaZ	b	c	ddeddededeedGee> d#efdfdgZ	ddhedePe, dGee> d#efdidjZ	k	ddedlePe, ded|ee= d#ef
dmdlZdne_ee	jdoZee	jdpZee	jÐdqZee	j9j:jĐdrZ		Y					ݐddsedtedued2e=dle=de=dve>dee> dee> ded#efdwdxZddddݐdydsedteduedzeeeegef  d2e=dve>ded#efd{d|Z		0	}	ddedle=de,de=d~ee d#efddZǐdePe, deded#dfddZ	0		0ddedee, d3ee, d2ee, d1ee, d#efddZ	0		0ddedee, dee, d3ee, d2ee, d1ee, d#efddZ	ddededededee d#ePe fddZ			ddededededededee dee dee d#e?eeef fddZee	j9j:j͐dj1di ed Z͐deded|edee dee de,fddZ	kddee dedee+ dede+de>d#ee fddZdee d#ee+ fddZАde	jde,de,d#dfddZ	k		k								k	ddeded|ede,de,dee dee dee dee de>de=dedee dme>dee de>dee de>dee dee dee dee dee de>de>d#e?eee f f4ddZdS (  zFunctional interface.    N)CallableOptionalTYPE_CHECKINGUnion)_VFsym_intTensor)_add_docstr_infer_size)	_overloadboolean_dispatchBroadcastingList1BroadcastingList2BroadcastingList3)reproducibility_notessparse_support_notes
tf32_notes)
_reductiongrad)_list_with_default_pair_single_triple)handle_torch_functionhas_torch_functionhas_torch_function_unaryhas_torch_function_variadic)_dtypeaz  
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.

{tf32_note}

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

Note:
    {cudnn_reproducibility_note}

Note:
    This operator supports complex data types i.e. ``complex32, complex64, complex128``.
ai  

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 string {'valid', 'same'},
      single number or a one-element tuple `(padW,)`. Default: 0
      ``padding='valid'`` is the same as no padding. ``padding='same'`` pads
      the input so the output has the same shape as the input. However, this mode
      doesn't support any stride values other than 1.

      .. warning::
          For ``padding='same'``, if the ``weight`` is even-length and
          ``dilation`` is odd in any dimension, a full :func:`pad` operation
          may be needed internally. Lowering performance.
    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::

    >>> inputs = torch.randn(33, 16, 30)
    >>> filters = torch.randn(20, 16, 5)
    >>> F.conv1d(inputs, filters)
ay  
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.

{tf32_note}

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

Note:
    {cudnn_reproducibility_note}

Note:
    This operator supports complex data types i.e. ``complex32, complex64, complex128``.
a  

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 string {'valid', 'same'},
      single number or a tuple `(padH, padW)`. Default: 0
      ``padding='valid'`` is the same as no padding. ``padding='same'`` pads
      the input so the output has the same shape as the input. However, this mode
      doesn't support any stride values other than 1.

      .. warning::
          For ``padding='same'``, if the ``weight`` is even-length and
          ``dilation`` is odd in any dimension, a full :func:`pad` operation
          may be needed internally. Lowering performance.

    dilation: the spacing between kernel elements. Can be a single number or
      a tuple `(dH, dW)`. Default: 1
    groups: split input into groups, both :math:`\text{in\_channels}` and :math:`\text{out\_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)
ay  
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.

{tf32_note}

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

Note:
    {cudnn_reproducibility_note}

Note:
    This operator supports complex data types i.e. ``complex32, complex64, complex128``.
a  

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 string {'valid', 'same'},
      single number or a tuple `(padT, padH, padW)`. Default: 0
      ``padding='valid'`` is the same as no padding. ``padding='same'`` pads
      the input so the output has the same shape as the input. However, this mode
      doesn't support any stride values other than 1.

      .. warning::
          For ``padding='same'``, if the ``weight`` is even-length and
          ``dilation`` is odd in any dimension, a full :func:`pad` operation
          may be needed internally. Lowering performance.

    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)
az  
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".

{tf32_note}

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

Note:
    {cudnn_reproducibility_note}
al  

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)
ay  
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".

{tf32_note}

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

Note:
    {cudnn_reproducibility_note}
a  

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)
ax  
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"

{tf32_note}

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

Note:
    {cudnn_reproducibility_note}
a  

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
Finputkernel_sizeoutput_sizeoutput_ratioreturn_indices_random_samplesreturnc              
   C   s   t | |rtt| |f| |||||dS |du r|du rtd|du rM|dus)J t|dkr3tdt|}t| d|d  t| d|d	  g}|du rm|  d
krYd	n| d}t	j
|| dd| j| jd}t	jj| |||S )a  
    fractional_max_pool2d(input, kernel_size, output_size=None, output_ratio=None, return_indices=False, _random_samples=None)

    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
    r    r!   r"   r#   NzRfractional_max_pool2d requires specifying either an output_size or an output_ratio   zWfractional_max_pool2d requires output_ratio to either be a single Int or tuple of Ints.r         dtypedevice)r   r   "fractional_max_pool2d_with_indices
ValueErrorlenr   intsizedimtorchrandr-   r.   _C_nnfractional_max_pool2dr   r   r    r!   r"   r#   _output_ration_batch r=   g/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/torch/nn/functional.pyr/     sB   
(
r/   c              
   C   <   t | |rtt| |f| |||||dS t| |||||d S Nr%   r   )r   r   r9   r/   r   r   r    r!   r"   r#   r=   r=   r>   _fractional_max_pool2d      

rB      r9   )arg_name	arg_indexdefaultif_trueif_falsemodule_name	func_namec              
   C   s   t | |rtt| |f| |||||dS |du r|du rtd|du rM|dus)J t|}t| d|d  t| d|d  t| d|d	  g}|du rm|  d
krYdn| d}tj	|| dd| j
| jd}tjj| |||S )a  
    fractional_max_pool3d(input, kernel_size, output_size=None, output_ratio=None, return_indices=False, _random_samples=None)

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

    Shape:
        - Input: :math:`(N, C, T_{in}, H_{in}, W_{in})` or :math:`(C, T_{in}, H_{in}, W_{in})`.
        - Output: :math:`(N, C, T_{out}, H_{out}, W_{out})` or :math:`(C, T_{out}, H_{out}, W_{out})`, where
          :math:`(T_{out}, H_{out}, W_{out})=\text{output\_size}` or
          :math:`(T_{out}, H_{out}, W_{out})=\text{output\_ratio} \times (T_{in}, H_{in}, W_{in})`

    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)   r(   r&   rD   r*   r,   )r   r   "fractional_max_pool3d_with_indicesr0   r   r2   r3   r4   r5   r6   r-   r.   r7   r8   fractional_max_pool3dr:   r=   r=   r>   rM   $  s<   
/
rM   c              
   C   r?   r@   )r   r   rN   rM   rA   r=   r=   r>   _fractional_max_pool3du  rC   rO   rN   r)   stridepaddingdilation	ceil_modec                 C   sR   t | rtt| f| ||||||d	S |du rtjtt g }t| |||||S )aS  
    max_pool1d(input, kernel_size, stride=None, padding=0, dilation=1, ceil_mode=False, return_indices=False)

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

    .. note::
        The order of :attr:`ceil_mode` and :attr:`return_indices` is different from
        what seen in :class:`~torch.nn.MaxPool1d`, and will change in a future release.

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

    Args:
        input: input tensor of shape :math:`(\text{minibatch} , \text{in\_channels} , iW)`, minibatch dim optional.
        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 negative infinity padding to be added on both sides, must be >= 0 and <= kernel_size / 2.
        dilation: The stride between elements within a sliding window, must be > 0.
        ceil_mode: If ``True``, will use `ceil` instead of `floor` to compute the output shape. This
                   ensures that every element in the input tensor is covered by a sliding window.
        return_indices: If ``True``, will return the argmax along with the max values.
                        Useful for :class:`torch.nn.functional.max_unpool1d` later
    rP   rQ   rR   rS   r"   N)r   r   max_pool1d_with_indicesr5   jitannotatelistr2   r   r   rP   rQ   rR   rS   r"   r=   r=   r>   rU     s"   "rU   c                 C   R   t | rtt| f| ||||||d	S |d u rtjtt g }t| |||||S NrT   )r   r   
max_pool1dr5   rV   rW   rX   r2   rY   r=   r=   r>   _max_pool1d     	r]      r\   c                 C   V   t | rtt| f| ||||||d	S |du rtjtt g }tjj	| |||||S )a`  
    max_pool2d(input, kernel_size, stride=None, padding=0, dilation=1, ceil_mode=False, return_indices=False)

    Applies a 2D max pooling over an input signal composed of several input
    planes.

    .. note::
        The order of :attr:`ceil_mode` and :attr:`return_indices` is different from
        what seen in :class:`~torch.nn.MaxPool2d`, and will change in a future release.

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

    Args:
        input: input tensor :math:`(\text{minibatch} , \text{in\_channels} , iH , iW)`, minibatch dim optional.
        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 negative infinity padding to be added on both sides, must be >= 0 and <= kernel_size / 2.
        dilation: The stride between elements within a sliding window, must be > 0.
        ceil_mode: If ``True``, will use `ceil` instead of `floor` to compute the output shape. This
                   ensures that every element in the input tensor is covered by a sliding window.
        return_indices: If ``True``, will return the argmax along with the max values.
                        Useful for :class:`torch.nn.functional.max_unpool2d` later
    rT   N)
r   r   max_pool2d_with_indicesr5   rV   rW   rX   r2   r7   r8   rY   r=   r=   r>   ra     "   "ra   c                 C   rZ   r[   )r   r   
max_pool2dr5   rV   rW   rX   r2   rY   r=   r=   r>   _max_pool2d'  r^   rd   rc   c                 C   r`   )ay  
    max_pool3d(input, kernel_size, stride=None, padding=0, dilation=1, ceil_mode=False, return_indices=False)

    Applies a 3D max pooling over an input signal composed of several input
    planes.

    .. note::
        The order of :attr:`ceil_mode` and :attr:`return_indices` is different from
        what seen in :class:`~torch.nn.MaxPool3d`, and will change in a future release.

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

    Args:
        input: input tensor :math:`(\text{minibatch} , \text{in\_channels} , iD, iH , iW)`, minibatch dim optional.
        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 negative infinity padding to be added on both sides, must be >= 0 and <= kernel_size / 2.
        dilation: The stride between elements within a sliding window, must be > 0.
        ceil_mode: If ``True``, will use `ceil` instead of `floor` to compute the output shape. This
                   ensures that every element in the input tensor is covered by a sliding window.
        return_indices: If ``True``, will return the argmax along with the max values.
                        Useful for :class:`torch.nn.functional.max_unpool3d` later
    rT   N)
r   r   max_pool3d_with_indicesr5   rV   rW   rX   r2   r7   r8   rY   r=   r=   r>   re   L  rb   re   c                 C   rZ   r[   )r   r   
max_pool3dr5   rV   rW   rX   r2   rY   r=   r=   r>   _max_pool3d  r^   rg   rf   c                 C   sF  |   }tjtt g }tt|D ]}||t| |  d ||  ||  d||    q|d u r:|}|S t|t|d krJ|dd  }t|t|krht	dt| dt|d  dt| dtt|D ]0}|| ||  }	|| ||  }
|	||   k r|
k sn t	d| d| d	|	 d
|
 d	qn|}|S )Nr)   r&   z,output_size should be a sequence containing z or z# elements, but it has a length of ''zinvalid output_size "z" (dim z must be between  and ))
r3   r5   rV   rW   rX   r2   ranger1   appendr0   )r   r   rP   rQ   r    
input_sizedefault_sizedretmin_sizemax_sizer=   r=   r>   _unpool_output_size  sF   

rs   indicesc              
   C   s   t | rtt| f| |||||dS t|}|durt|}n|}t|}t| ||||}t|tr7|dg }n|d }tjj	
| d|d|dS )zjCompute a partial inverse of :class:`MaxPool1d`.

    See :class:`~torch.nn.MaxUnpool1d` for details.
    rP   rQ   r    Nr)   )r)   r(   )r   r   max_unpool1dr   rs   
isinstancerX   r5   r7   r8   max_unpool2d	unsqueezesqueezer   rt   r   rP   rQ   r    _strider=   r=   r>   rv     s2   


rv   c              
   C   sj   t | rtt| f| |||||dS t|}|durt|}n|}t|}t| ||||}tjj| ||S )zjCompute a partial inverse of :class:`MaxPool2d`.

    See :class:`~torch.nn.MaxUnpool2d` for details.
    ru   N)r   r   rx   r   rs   r5   r7   r8   r{   r=   r=   r>   rx     s$   

rx   c              
   C   sn   t | rtt| f| |||||dS t|}|durt|}n|}t|}t| ||||}tjj| ||||S )zjCompute a partial inverse of :class:`MaxPool3d`.

    See :class:`~torch.nn.MaxUnpool3d` for details.
    ru   N)r   r   max_unpool3dr   rs   r5   r7   r8   r{   r=   r=   r>   r}     s$   

r}   	norm_typec           	   	   C   s   t | rtt| f| ||||dS t|\}}}|dur't| |||d|}nt| ||d|d}t|tt	| 
|| | d| S )z
    Apply a 3D 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.LPPool3d` for details.
    rP   rS   Nr   rQ   rS         ?)r   r   	lp_pool3dr   
avg_pool3dpowr5   signreluabsmul)	r   r~   r   rP   rS   kdkwkhoutr=   r=   r>   r   4  s$   	.r   c              	   C   s   t | rtt| f| ||||dS t|\}}|dur&t| |||d|}nt| ||d|d}t|tt	| 
|| d| S )z
    Apply 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   Nr   r   r   )r   r   	lp_pool2dr   
avg_pool2dr   r5   r   r   r   r   )r   r~   r   rP   rS   r   r   r   r=   r=   r>   r   Z  s"   	,r   c              	   C   s~   t | rtt| f| ||||dS |dur t| |||d|}nt| ||d|d}t|tt| 	|d| S )zApply 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.
    r   Nr   r   r   )
r   r   	lp_pool1d
avg_pool1dr   r5   r   r   r   r   )r   r~   r   rP   rS   r   r=   r=   r>   r   ~  s"   	&r   c                 C   s(   t | rtt| f| ||dS t| |S )a  
    adaptive_max_pool1d(input, output_size, return_indices=False)

    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    adaptive_max_pool1d_with_indicesr5   adaptive_max_pool1dr   r    r"   r=   r=   r>   r     s   r   c                 C   *   t | rtt| f| ||dS t| |d S Nr   r   )r   r   r   r   r   r=   r=   r>   _adaptive_max_pool1d     r   r&   r   c                 C   :   t | rtt| f| ||dS t||  }tjj| |S )a  adaptive_max_pool2d(input, output_size, return_indices=False)

    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``
    r   )	r   r    adaptive_max_pool2d_with_indicesr   r3   r5   r7   r8   adaptive_max_pool2dr   r=   r=   r>   r     s   r   c                 C   r   r   )r   r   r   r   r   r=   r=   r>   _adaptive_max_pool2d  r   r   r   c                 C   r   )a  
    adaptive_max_pool3d(input, output_size, return_indices=False)

    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``
    r   )	r   r    adaptive_max_pool3d_with_indicesr   r3   r5   r7   r8   adaptive_max_pool3dr   r=   r=   r>   r     s   r   c                 C   r   r   )r   r   r   r   r   r=   r=   r>   _adaptive_max_pool3d/  r   r   r   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   6   t | rtt| f| |S t||  }tjj| |S )a  Apply 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   adaptive_avg_pool2dr   r3   r5   r7   r8   r   r    _output_sizer=   r=   r>   r   Z     	r   c                 C   r   )a  Apply 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   adaptive_avg_pool3dr   r3   r5   r7   r8   r   r=   r=   r>   r   i  r   r         ?Tptraininginplacec                 C   \   t | rtt| f| |||dS |dk s|dkrtd| |r't| ||S t| ||S )a  During training, randomly zeroes some elements of the input tensor with probability :attr:`p`.

    Uses 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``
    r   r   r           r   7dropout probability has to be between 0 and 1, but got )r   r   dropoutr0   r   dropout_r   r   r   r   r=   r=   r>   r   y  s   r   c                 C   r   )z\Apply alpha dropout to the input.

    See :class:`~torch.nn.AlphaDropout` for details.
    r   r   r   r   )r   r   alpha_dropoutr0   r   alpha_dropout_r   r=   r=   r>   r     s   
r   c                 C   s   t | rtt| f| |||dS |dk s|dkrtd| |  }|dvr.td| d|dk}|s@|r;| d	n| d	} |rIt	| ||nt
| ||}|s^|rY|d	n|d	}|S )
a  Randomly zero out entire channels (a channel is a 1D feature map).

    For example, the :math:`j`-th channel of the :math:`i`-th sample in the
    batched input is a 1D 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.Dropout1d` 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   r   r   r&   r*   z3dropout1d: Expected 2D or 3D input, but received a zD input. Note that dropout1d exists to provide channel-wise dropout on inputs with 1 spatial dimension, a channel dimension, and an optional batch dimension (i.e. 2D or 3D inputs).r*   r   )r   r   	dropout1dr0   r4   RuntimeError
unsqueeze_ry   r   feature_dropout_feature_dropoutsqueeze_rz   )r   r   r   r   inp_dim
is_batchedresultr=   r=   r>   r     s*   
r   c                 C   s   t | rtt| f| |||dS |dk s|dkrtd| |  }|dvr1d| d}t| |dkr:td	 |rEt| ||}|S t	| ||}|S )
a  Randomly zero out entire channels (a channel is a 2D feature map).

    For example, 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   r   r   )r*   rD   zdropout2d: Received a aU  -D input to dropout2d, which is deprecated and will result in an error in a future release. To retain the behavior and silence this warning, please use dropout instead. Note that dropout2d exists to provide channel-wise dropout on inputs with 2 spatial dimensions, a channel dimension, and an optional batch dimension (i.e. 3D or 4D inputs).r*   a  dropout2d: Received a 3D input to dropout2d and assuming that channel-wise 1D dropout behavior is desired - input is interpreted as shape (N, C, L), where C is the channel dim. This behavior will change in a future release to interpret the input as one without a batch dimension, i.e. shape (C, H, W). To maintain the 1D channel-wise dropout behavior, please switch to using dropout1d instead.)
r   r   	dropout2dr0   r4   warningswarnr   r   r   )r   r   r   r   r   warn_msgr   r=   r=   r>   r     s,   


r   c                 C   s   t | rtt| f| |||dS |dk s|dkrtd| |  }|dvr1d| d}t| |dk}|sC|r>| d	n| d	} |rLt	
| ||nt	| ||}|sa|r\|d	n|d	}|S )
a  Randomly zero out entire channels (a channel is a 3D feature map).

    For example, 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   r   r   )rD      zdropout3d: Received a aU  -D input to dropout3d, which is deprecated and will result in an error in a future release. To retain the behavior and silence this warning, please use dropout instead. Note that dropout3d exists to provide channel-wise dropout on inputs with 3 spatial dimensions, a channel dimension, and an optional batch dimension (i.e. 4D or 5D inputs).r   r   )r   r   	dropout3dr0   r4   r   r   r   ry   r   r   r   r   rz   )r   r   r   r   r   r   r   r   r=   r=   r>   r     s*   

r   c                 C   r   )a  Randomly masks out entire channels (a channel is a feature map).

    For example, 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   r   r   )r   r   feature_alpha_dropoutr0   r   feature_alpha_dropout_r   r=   r=   r>   r   N  s    r   	thresholdvaluec                 C   sF   t | rtt| f| |||dS |rt| ||}|S t| ||}|S )zsApply a threshold to each element of the input Tensor.

    See :class:`~torch.nn.Threshold` for more details.
    r   )r   r   
_thresholdr   
threshold_r   )r   r   r   r   r   r=   r=   r>   r   y  s   
r   zX
threshold_(input, threshold, value) -> Tensor

In-place version of :func:`~threshold`.
c                 C   :   t | rtt| f| |dS |rt| }|S t| }|S )zrelu(input, inplace=False) -> Tensor

    Applies the rectified linear unit function element-wise. See
    :class:`~torch.nn.ReLU` for more details.
    r   )r   r   r   r5   relu_r   r   r   r=   r=   r>   r     s   

r   z<
relu_(input) -> Tensor

In-place version of :func:`~relu`.
r(   r4   c                 C   s>   t | rtt| f| |dS |  dkrt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
    r4   r   z>glu does not support scalars because halving size must be even)r   r   glur4   r   r5   r7   r8   )r   r4   r=   r=   r>   r     s   r         r   min_valmax_valc                 C   s^   t | rtt| f| |||dS ||krtd|r$tjj| ||}|S 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   z&min_val cannot be greater than max_val)r   r   hardtanhr0   r5   r7   r8   	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   sB   t | rtt| f| |dS |rtjj| }|S tjj| }|S )zrelu6(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   r   relu6r5   r7   r8   relu6_r   r=   r=   r>   r     s   r   alphac                 C   H   t | rtt| f| ||dS |rtjj| |}|S tjj| |}|S )zuApply the Exponential Linear Unit (ELU) function element-wise.

    See :class:`~torch.nn.ELU` for more details.
    r   r   )r   r   elur5   r7   r8   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   r   )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   selur5   selu_r   r=   r=   r>   r     s   


r   z<
selu_(input) -> Tensor

In-place version of :func:`~selu`.
c                 C   s@   t | rtt| f| ||dS |rt| |}|S t| |}|S )zcelu(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   celur5   celu_r   r=   r=   r>   r   9  s   r   zF
celu_(input, alpha=1.) -> Tensor

In-place version of :func:`~celu`.
{Gz?negative_slopec                 C   r   )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   
leaky_relur5   r7   r8   leaky_relu_)r   r   r   r   r=   r=   r>   r   Z  s   r   z]
leaky_relu_(input, negative_slope=0.01) -> Tensor

In-place version of :func:`~leaky_relu`.
a  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.

.. note::
    `weight` is expected to be a scalar or 1-D tensor. If `weight` is 1-D,
    its size must match the number of input channels, determined by
    `input.size(1)` when `input.dim() >= 2`, otherwise 1.
    In the 1-D case, note that when `input` has dim > 2, `weight` can be expanded
    to the shape of `input` in a way that is not possible using normal
    :ref:`broadcasting semantics<broadcasting-semantics>`.

See :class:`~torch.nn.PReLU` for more details.
      ?UUUUUU?lowerupperc              	   C   sL   t | rtt| f| ||||dS |rt| |||}|S t| |||}|S )zrrelu(input, lower=1./8, upper=1./3, training=False, inplace=False) -> Tensor

    Randomized leaky ReLU.

    See :class:`~torch.nn.RReLU` for more details.
    )r   r   r   r   )r   r   rrelur5   rrelu_)r   r   r   r   r   r   r=   r=   r>   r     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.
a  
gelu(input, approximate = 'none') -> Tensor

When the approximate argument is 'none', it applies element-wise the function
:math:`\text{GELU}(x) = x * \Phi(x)`

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

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

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

See `Gaussian Error Linear Units (GELUs) <https://arxiv.org/abs/1606.08415>`_.
z
hardshrink(input, lambd=0.5) -> Tensor

Applies the hard shrinkage function element-wise

See :class:`~torch.nn.Hardshrink` for more details.
c                 C   s"   t | rtt| f| S | |   S )ztanhshrink(input) -> Tensor

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

    See :class:`~torch.nn.Tanhshrink` for more details.
    )r   r   
tanhshrinktanhr   r=   r=   r>   r     s   r   c                 C   s&   t | rtt| f| S | |  d  S )zsoftsign(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   softsignr   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.
namendim
stacklevelc                 C   s>   t jd|  d|d |dks|dks|dkrd}|S d}|S )NzImplicit dimension choice for zF has been deprecated. Change the call to include dim=X as an argument.r   r   r)   r*   )r   r   )r   r   r   rp   r=   r=   r>   _get_softmax_dim	  s   
r   r*   _stacklevelr-   c                 C   sb   t | rtt| f| |||dS |du rtd|  |}|du r'|  |}|S |  j||d}|S )at  Apply 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.

    Args:
        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.
    r4   r   r-   Nsoftminr-   )r   r   r   r   r4   softmaxr   r4   r   r-   rp   r=   r=   r>   r     s   r   c                 C   ^   t | rtt| f| |||dS |du rtd|  |}|du r&| |}|S | j||d}|S )a  Apply 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.

    Args:
        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   r4   r   r=   r=   r>   r   7  s   
r   绽|=logitstauhardepsc           
   	   C   s   t | rtt| f| ||||dS |dkrtd tj| tjd 	  }| | | }|
|}|rS|j|ddd }tj| tjd||d}||  | }	|	S |}	|	S )	a  
    Sample from the Gumbel-Softmax distribution (`Link 1`_  `Link 2`_) and optionally discretize.

    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
    )r   r   r   r4   r   z0`eps` parameter is deprecated and has no effect.)memory_formatTkeepdimr)   r   )r   r   gumbel_softmaxr   r   r5   
empty_likelegacy_contiguous_formatexponential_logr   max
zeros_likescatter_detach)
r   r   r   r   r4   gumbelsy_softindexy_hardrp   r=   r=   r>   r  b  s0   .


r  c                 C   r   )a  Apply 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.

    Args:
        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 cast 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   r4   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 )ztanh(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.
    )r   r   r=   r=   r>   r     s   r   c                 C   r  )zsigmoid(input) -> Tensor

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

    See :class:`~torch.nn.Sigmoid` for more details.
    )sigmoidr   r=   r=   r>   r    s   r  c                 C   :   t | rtt| f| |dS |rtjj| S tjj| S )a  Apply the Hardsigmoid function element-wise.

    .. 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   hardsigmoidr5   r7   r8   hardsigmoid_r   r   r=   r=   r>   r    s
   r  au  
linear(input, weight, bias=None) -> Tensor

Applies a linear transformation to the incoming data: :math:`y = xA^T + b`.

This operation supports 2-D :attr:`weight` with :ref:`sparse layout<sparse-docs>`

{sparse_beta_warning}

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

Shape:

    - Input: :math:`(*, in\_features)` where `*` means any number of
      additional dimensions, including none
    - Weight: :math:`(out\_features, in\_features)` or :math:`(in\_features)`
    - Bias: :math:`(out\_features)` or :math:`()`
    - Output: :math:`(*, out\_features)` or :math:`(*)`, based on the shape of the weight
a  
bilinear(input1, input2, weight, bias=None) -> Tensor

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.
c                 C   r  )a  Apply the Sigmoid Linear Unit (SiLU) function, element-wise.

    The SiLU function is also known as the swish function.

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

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

    See :class:`~torch.nn.SiLU` for more details.
    r   )r   r   silur5   r7   r8   silu_r  r=   r=   r>   r  6	  
   r  c                 C   r  )au  Apply the Mish function, element-wise.

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

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

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

    See :class:`~torch.nn.Mish` for more details.
    r   )r   r   mishr5   r7   r8   mish_r  r=   r=   r>   r  O	  s
   r  c                 C   r  )a  Apply hardswish function, element-wise.

    Follows implementation 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   	hardswishr5   r7   r8   
hardswish_r  r=   r=   r>   r  c	  r  r  weightmax_normc                 C   s   t |  ||| d S N)r5   embedding_renorm_r
  )r  r   r  r~   r=   r=   r>   _no_grad_embedding_renorm_|	  s   r!         @padding_idxscale_grad_by_freqsparsec                 C   s   t | |rtt| |f| ||||||d	S |dur@|dkr(||dk s'J dn|dk r?||d ks8J d|d| }nd}|durQ|  } t|| || t|| |||S )aw  Generate 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.

    .. note::
        Note that the analytical gradients of this function with respect to
        entries in :attr:`weight` at the row specified by :attr:`padding_idx`
        are expected to differ from the numerical ones.

    .. note::
        Note that `:class:`torch.nn.Embedding` differs from this function in
        that it initializes the row of :attr:`weight` specified by
        :attr:`padding_idx` to all zeros on construction.

    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 specified, the entries at :attr:`padding_idx` do not contribute to the gradient;
                                     therefore, the embedding vector at :attr:`padding_idx` is not updated during training,
                                     i.e. it remains as a fixed "pad".
        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 (bool, 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)
        >>> # xdoctest: +IGNORE_WANT("non-deterministic")
        >>> 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]]])
    )r#  r  r~   r$  r%  Nr   z)Padding_idx must be within num_embeddingsr(   )r   r   	embeddingr3   
contiguousr!  r5   )r   r  r#  r  r~   r$  r%  r=   r=   r>   r&  	  s@   
N
r&  meanoffsetsmodeper_sample_weightsinclude_last_offsetc                 C   s~  t | |||rtt| |||f| |||||||||	|
dS |jtjkr0|  r0td | |}} |durI| 	 |	 krIt
d|j d| j d| dksXt
d|  tj s|  dkr| jrd	}	|  }|  d
} |dur|js~t
d| d
}n`|  dkr|durd}tj stt|}t
d| tjd|  | 	d| j| jd}| d
} |dur|d
}n"|  dkr|du rt
d| dkrt
dn	t
d|   |dkrd}n!|dkrd}n|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| dt|| ||||||	|
	\}}}}|S )aW  Compute sums, means or maxes of `bags` of embeddings.

    Calculation is done without instantiating the intermediate embeddings.
    See :class:`torch.nn.EmbeddingBag` for more details.

    Note:
        {backward_reproducibility_note}

    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 (bool, 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 (str, 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).

        padding_idx (int, optional): If specified, the entries at :attr:`padding_idx` do not contribute to the
                                     gradient; therefore, the embedding vector at :attr:`padding_idx` is not updated
                                     during training, i.e. it remains as a fixed "pad". Note that the embedding
                                     vector at :attr:`padding_idx` is excluded from the reduction.

    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])
        >>> # xdoctest: +IGNORE_WANT("non-deterministic")
        >>> F.embedding_bag(input, embedding_matrix, offsets)
        tensor([[ 0.3397,  0.3552,  0.5545],
                [ 0.5893,  0.4386,  0.5882]])

        >>> # example with padding_idx
        >>> embedding_matrix = torch.rand(10, 3)
        >>> input = torch.tensor([2, 2, 2, 2, 4, 3, 2, 9])
        >>> offsets = torch.tensor([0, 4])
        >>> F.embedding_bag(input, embedding_matrix, offsets, padding_idx=2, mode='sum')
        tensor([[ 0.0000,  0.0000,  0.0000],
                [-0.7082,  3.2145, -2.6251]])
    )	r)  r  r~   r$  r*  r%  r+  r,  r#  zArgument order of nn.functional.embedding_bag was changed. Usage `embedding_bag(weight, input, ...)` is deprecated, and should now be `embedding_bag(input, weight, ...)`.Nz&embedding_bag: If per_sample_weights (z>) is not None, then it must have the same shape as the input (rj   r&   z:weight has to be a 2D Tensor, but got Tensor of dimension Tr(   zGIf input is nested, then per_sample_weights must be nested if specifiedz	<unknown>zif 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,   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 maxzoembedding_bag: per_sample_weights was not None. per_sample_weights is only supported for mode='sum' (got mode='z,'). Please open a feature request on GitHub.)r   r   embedding_bagr-   r5   longis_floating_pointr   r   r3   r0   shaper4   rV   is_scripting	is_nestedr)  valuesreshapestrtypearangenumelr.   r!  NotImplementedError)r   r  r)  r  r~   r$  r*  r%  r+  r,  r#  type_str	mode_enumrp   _r=   r=   r>   r.  	  s   \







r.  r3   c                 C   sH   | d }t t| d D ]
}|| |d  9 }q|dkr"td|  d S )Nr   r&   r)   zEExpected more than 1 value per channel when training, got input size rk   r1   r0   r3   
size_prodsir=   r=   r>   _verify_batch_size
  s   
rB  皙?h㈵>running_meanrunning_varbiasmomentumc                 C   f   t | ||||rtt| ||||f| |||||||d
S |r#t|   t| |||||||tjjj	S )zApply 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  rG  r   rH  r   )	r   r   
batch_normrB  r3   r5   backendscudnnenabled)r   rE  rF  r  rG  r   rH  r   r=   r=   r>   rJ  
  s4   rJ  c                 C   s>   d}t dt| D ]}|| | 9 }q	|dkrtd|  d S )Nr)   r&   zCExpected more than 1 spatial element when training, got input size r>  r?  r=   r=   r>   _verify_spatial_size  s   rN  use_input_statsc                 C   rI  )zApply Instance Normalization independently for each channel in every data sample within a batch.

    See :class:`~torch.nn.InstanceNorm1d`, :class:`~torch.nn.InstanceNorm2d`,
    :class:`~torch.nn.InstanceNorm3d` for details.
    )rE  rF  r  rG  rO  rH  r   )	r   r   instance_normrN  r3   r5   rK  rL  rM  )r   rE  rF  r  rG  rO  rH  r   r=   r=   r>   rP    s4   rP  normalized_shapec              	   C   sB   t | ||rtt| ||f| ||||dS t| ||||tjjjS )zxApply Layer Normalization for last certain number of dimensions.

    See :class:`~torch.nn.LayerNorm` for details.
    r  rG  r   )r   r   
layer_normr5   rK  rL  rM  )r   rQ  r  rG  r   r=   r=   r>   rS  I  s   	rS  c                 C   s2   t | |rtt| |f| |||dS t| |||S )zaApply Root Mean Square Layer Normalization.

    See :class:`~torch.nn.RMSNorm` for details.
    )r  r   )r   r   rms_normr5   )r   rQ  r  r   r=   r=   r>   rT  c  s
   

rT  
num_groupsc              	   C   s   t | ||rtt| ||f| ||||dS |  dk r#td|   t| d| d | |gt|  dd   t| ||||tj	j
jS )zxApply Group Normalization for last certain number of dimensions.

    See :class:`~torch.nn.GroupNorm` for details.
    rR  r&   z=Expected at least 2 dimensions for input tensor but received r   r)   N)r   r   
group_normr4   r   rB  r3   rX   r5   rK  rL  rM  )r   rU  r  rG  r   r=   r=   r>   rV  t  s2   rV  -C6?      ?betakc              	   C   s.  t | rtt| f| ||||dS |  }|dk r td| d|  dkr(| S | | }|dkrR|d}t|dd|d |d d f}t	||dfdd
d}n6|  }||d d|d |d d	}t|dddd|d |d d f}t||ddfdd
d}||}||||}| | S )
a  Apply local response normalization over an input signal.

    The input signal is composed of several input planes, where channels occupy the second dimension.
    Normalization is applied across channels.

    See :class:`~torch.nn.LocalResponseNorm` for details.
    )r   rY  rZ  r*   zIExpected 3D or higher dimensionality                          input (got z dimensions)r   r)   r&   )rP   r(   )r   r   local_response_normr4   r0   r9  r   ry   padr   rz   r3   viewr   addr   )r   r3   r   rY  rZ  r4   divsizesr=   r=   r>   r[    s.   


"
r[  	log_probstargetsinput_lengthstarget_lengthsblank	reductionzero_infinityc                 C   sL   t | |||rtt| |||f| ||||||d	S t| ||||t||S )a  Apply the Connectionist Temporal Classification loss.

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

    Note:
        {cudnn_reproducibility_note}

    Note:
        {backward_reproducibility_note}

    Args:
        log_probs: :math:`(T, N, C)` or :math:`(T, 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)` or :math:`()`.
            Lengths of the inputs (must each be :math:`\leq T`)
        target_lengths: :math:`(N)` or :math:`()`.
            Lengths of the targets
        blank (int, optional):
            Blank label. Default :math:`0`.
        reduction (str, 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()
    )re  rf  rg  )r   r   ctc_lossr5   
_Reductionget_enum)ra  rb  rc  rd  re  rf  rg  r=   r=   r>   rh    s*   4
rh  targetsize_averageignore_indexreducec                 C   sd   t | ||rtt| ||f| ||||||d	S |dus|dur$t||}tjj| ||t	||S )a%
  Compute 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. `input` is expected to be log-probabilities.
        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 (str, 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, dim=1), target)
        >>> output.backward()
    )r  rm  rn  ro  rf  N)
r   r   nll_lossri  legacy_get_stringr5   r7   r8   nll_loss_ndrj  )r   rl  r  rm  rn  ro  rf  r=   r=   r>   rp    s"   2rp  :0yE>	log_inputfullc           	      C   s   t | |rtt| |f| |||||||d
S |dus|dur#t||}|dkr7|dkr7|dkr7| }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 (str, 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'``

    )rt  ru  rm  r   ro  rf  Nnoner(  r-  # is not a valid value for reduction)r   r   poisson_nll_lossri  rq  r0   r5   rj  )	r   rl  rt  ru  rm  r   ro  rf  rp   r=   r=   r>   rx  [  s,   
*rx  ư>varc              
   C   s  t | ||rtt| ||f| |||||dS t|tr*|dk r"td|t|  }nt|dk r5td|	 | 	 krl| 	 dd |	 krPt
|d}n| 	 dd |	 dd krh|	ddkrhntd|dkr~|d	kr~|d
kr~t|d | }t  |j|d W d   n1 sw   Y  dt|| | d |   }|r|dtdtj  7 }|d	kr| S |d
kr| S |S )a  Gaussian negative log likelihood loss.

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

    Args:
        input: expectation of the Gaussian distribution.
        target: sample from the Gaussian distribution.
        var: tensor of positive variance(s), one for each of the expectations
            in the input (heteroscedastic), or a single one (homoscedastic),
            or a positive scalar value to be used for all expectations.
        full (bool, optional): include the constant term in the loss calculation. Default: ``False``.
        eps (float, optional): value added to var, for stability. Default: 1e-6.
        reduction (str, optional): specifies the reduction to apply to the output:
            ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
            ``'mean'``: the output is the average of all batch member losses,
            ``'sum'``: the output is the sum of all batch member losses.
            Default: ``'mean'``.
    )ru  r   rf  r   zvar has negative entry/entriesNr(   r)   zvar is of incorrect sizerv  r(  r-   is not valid)minr   r&   )r   r   gaussian_nll_lossrw   floatr0   r5   	ones_likeanyr3   ry   cloneno_gradclamp_r  mathpir(  r-  )r   rl  rz  ru  r   rf  lossr=   r=   r>   r}    sJ   
.
r}  
log_targetc              
   C   s   t | |rtt| |f| |||||dS |dus|dur"t||}n|dkr+td |dkr5td}nt|}tj| |||d}|dkrU| 	 dkrU|| 
 d  }|S )	a 	  Compute the KL Divergence loss.

    Refer - 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 in log-probabilities.
        target: Tensor of the same shape as input. See :attr:`log_target` for
            the target's interpretation.
        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 (str, 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`.

    .. warning::
        :attr:`reduction` = ``'mean'`` doesn't return the true kl divergence value, please use
        :attr:`reduction` = ``'batchmean'`` which aligns with KL math definition.
    )rm  ro  rf  r  Nr(  zreduction: '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.	batchmeanr-  )r  r   )r   r   kl_divri  legacy_get_enumr   r   rj  r5   r4   r3   )r   rl  rm  ro  rf  r  reduction_enumreducedr=   r=   r>   r    s0   
0

r  r   label_smoothingc                 C   sh   t | ||rtt| ||f| |||||||d
S |dus|dur%t||}tjj| ||t	|||S )a  Compute the cross entropy loss between input logits and target.

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

    Args:
        input (Tensor) : Predicted unnormalized logits;
            see Shape section below for supported shapes.
        target (Tensor) : Ground truth class indices or class probabilities;
            see Shape section below for supported shapes.
        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. Note that
            :attr:`ignore_index` is only applicable when the target contains class indices.
            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 (str, 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'``
        label_smoothing (float, optional): A float in [0.0, 1.0]. Specifies the amount
            of smoothing when computing the loss, where 0.0 means no smoothing. The targets
            become a mixture of the original ground truth and a uniform distribution as described in
            `Rethinking the Inception Architecture for Computer Vision <https://arxiv.org/abs/1512.00567>`__. Default: :math:`0.0`.

    Shape:
        - Input: Shape :math:`(C)`, :math:`(N, C)` or :math:`(N, C, d_1, d_2, ..., d_K)` with :math:`K \geq 1`
          in the case of `K`-dimensional loss.
        - Target: If containing class indices, shape :math:`()`, :math:`(N)` or :math:`(N, d_1, d_2, ..., d_K)` with
          :math:`K \geq 1` in the case of K-dimensional loss where each value should be between :math:`[0, C)`.
          If containing class probabilities, same shape as the input and each value should be between :math:`[0, 1]`.

        where:

        .. math::
            \begin{aligned}
                C ={} & \text{number of classes} \\
                N ={} & \text{batch size} \\
            \end{aligned}

    Examples::

        >>> # Example of target with class indices
        >>> input = torch.randn(3, 5, requires_grad=True)
        >>> target = torch.randint(5, (3,), dtype=torch.int64)
        >>> loss = F.cross_entropy(input, target)
        >>> loss.backward()
        >>>
        >>> # Example of target with class probabilities
        >>> input = torch.randn(3, 5, requires_grad=True)
        >>> target = torch.randn(3, 5).softmax(dim=1)
        >>> loss = F.cross_entropy(input, target)
        >>> loss.backward()
    )r  rm  rn  ro  rf  r  N)
r   r   cross_entropyri  rq  r5   r7   r8   cross_entropy_lossrj  )r   rl  r  rm  rn  ro  rf  r  r=   r=   r>   r  L  s.   Kr  c              
   C   s   t | ||rtt| ||f| |||||dS |dus|dur$t||}nt|}| |  kr@td|  d|   d|durRt| | }|	|}t
jj| |||S )a  Measure Binary Cross Entropy between the target and input probabilities.

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

    Args:
        input: Tensor of arbitrary shape as probabilities.
        target: Tensor of the same shape as input with values between 0 and 1.
        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 (str, 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(torch.sigmoid(input), target)
        >>> loss.backward()
    r  rm  ro  rf  NUsing a target size (') that is different to the input size (z7) is deprecated. Please ensure they have the same size.)r   r   binary_cross_entropyri  r  rj  r3   r0   r
   expandr5   r7   r8   )r   rl  r  rm  ro  rf  r  new_sizer=   r=   r>   r    s,   (


r  
pos_weightc                 C   s   t | |||rtt| |||f| ||||||d	S |dus |dur't||}nt|}| |  ksCtd|  d|   dt| ||||S )aw
  Calculate Binary Cross Entropy between target and input logits.

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

    Args:
        input: Tensor of arbitrary shape as unnormalized scores (often referred to as logits).
        target: Tensor of the same shape as input with values between 0 and 1
        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 (str, 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 to be broadcasted with target.
            Must be a tensor with equal size along the class dimension to the number of classes.
            Pay close attention to PyTorch's broadcasting semantics in order to achieve the desired
            operations. For a target of size [B, C, H, W] (where B is batch size) pos_weight of
            size [B, C, H, W] will apply different pos_weights to each element of the batch or
            [C, H, W] the same pos_weights across the batch. To apply the same positive weight
            along all spatial dimensions for a 2D multi-class target [C, H, W] use: [C, 1, 1].
            Default: ``None``

    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()
    )r  rm  ro  rf  r  NzTarget size (z") must be the same as input size (rj   )	r   r    binary_cross_entropy_with_logitsri  r  rj  r3   r0   r5   )r   rl  r  rm  ro  rf  r  r  r=   r=   r>   r    s,   1


r  c              
   C   s   t | |rtt| |f| |||||dS | |  ks-tjd|  d|   ddd |dus5|dur;t||}t	| |\}}|dkrStj
j||t|S tj
j||t||S )	zCompute the Smooth L1 loss.

    Function 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.
    )rm  ro  rf  rY  r  r  i). This will likely lead to incorrect results due to broadcasting. Please ensure they have the same size.r&   r   Nr   )r   r   smooth_l1_lossr3   r   r   ri  rq  r5   broadcast_tensorsr7   r8   l1_lossrj  )r   rl  rm  ro  rf  rY  expanded_inputexpanded_targetr=   r=   r>   r  @  s4   

r  deltac           	   	   C   s  t | ||rtt| ||f| ||||dS | |  ks.tjd|  d|   ddd t| |\}}|du rGtjj	||t
||S | |  krStdtjj	||t
d	|}|| }|d	krj|S |d
krst|S |dkr{| S td| d)aj  huber_loss(input, target, reduction='mean', delta=1.0, weight=None) -> Tensor

    Computes the Huber loss, with optional weighting.

    Function uses a squared term if the absolute
    element-wise error falls below delta and a delta-scaled L1 term otherwise.

    When delta equals 1, this loss is equivalent to SmoothL1Loss.
    In general, Huber loss differs from SmoothL1Loss by a factor of delta (AKA beta in Smooth L1).

    Args:
        input (Tensor): Predicted values.
        target (Tensor): Ground truth values.
        reduction (str, optional): Specifies the reduction to apply to the output:
                                   'none' | 'mean' | 'sum'. 'mean': the mean of the output is taken.
                                   'sum': the output will be summed. 'none': no reduction will be applied.
                                   Default: 'mean'.
        delta (float, optional): The threshold at which to change between delta-scaled L1 and L2 loss. Default: 1.0.
        weight (Tensor, optional): Weights for each sample. Default: None.

    Returns:
        Tensor: Huber loss (optionally weighted).
    )rf  r  r  r  r  r  r&   r   N*Weights and input must have the same size.rv  r-  r(  Invalid reduction mode: (. Expected one of 'none', 'mean', 'sum'.)r   r   
huber_lossr3   r   r   r5   r  r7   r8   ri  rj  r0   r-  r(  )	r   rl  rf  r  r  r  r  unweighted_lossweighted_lossr=   r=   r>   r  p  sF   


r  c           
   	   C   s  t | |rtt| ||f| ||||dS | |  ks-tjd|  d|   ddd |dus5|dur;t||}t	| |\}}|dur| |  krSt
dt|| }|| }	|d	krd|	S |d
krmt|	S |dkr{t|	t| S t
d| dtjj||t|S )zl1_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.
    rm  ro  rf  r  r  r  r&   r   Nr  rv  r-  r(  r  r  )r   r   r  r3   r   r   ri  rq  r5   r  r0   r   r-  r7   r8   rj  )
r   rl  rm  ro  rf  r  r  r  absolute_errorsweighted_absolute_errorsr=   r=   r>   r    sF   
	

r  c           
   
   C   s$  t | ||rtt| ||f| |||||dS | |  ks/tjd|  d|   ddd |dus7|dur=t||}t	| |\}}|dur| |  krUt
dt|| d}|| }	|d	krg|	S |d
krpt|	S |dkr~t|	t| S t
d| dtjj||t|S )a  mse_loss(input, target, size_average=None, reduce=None, reduction='mean', weight=None) -> Tensor

    Measures the element-wise mean squared error, with optional weighting.

    Args:
        input (Tensor): Predicted values.
        target (Tensor): Ground truth values.
        size_average (bool, optional): Deprecated (use reduction).
        reduce (bool, optional): Deprecated (use reduction).
        reduction (str, optional): Specifies the reduction to apply to the output:
                                   'none' | 'mean' | 'sum'. 'mean': the mean of the output is taken.
                                   'sum': the output will be summed. 'none': no reduction will be applied.
                                   Default: 'mean'.
        weight (Tensor, optional): Weights for each sample. Default: None.

    Returns:
        Tensor: Mean Squared Error loss (optionally weighted).
    )rm  ro  rf  r  r  r  r  r&   r   Nr  rv  r-  r(  r  r  )r   r   mse_lossr3   r   r   ri  rq  r5   r  r0   r   r-  r7   r8   rj  )
r   rl  rm  ro  rf  r  r  r  squared_errorsweighted_squared_errorsr=   r=   r>   r    sH   

r  input1input2marginc                 C   s   t | ||rtt| ||f| ||||||d	S |dus|dur%t||}nt|}|  | ks:|  | krNtd|   d|  d|  dt	| ||||S )zmargin_ranking_loss(input1, input2, target, margin=0, size_average=None, reduce=None, reduction='mean') -> Tensor

    See :class:`~torch.nn.MarginRankingLoss` for details.
    r  rm  ro  rf  NzZmargin_ranking_loss : All input tensors should have same dimension but got sizes: input1: z
, input2: z
, target:  )
r   r   margin_ranking_lossri  r  rj  r4   r   r3   r5   r  r  rl  r  rm  ro  rf  r  r=   r=   r>   r  F  s4   
 r  c              
   C   s^   t | |rtt| |f| |||||dS |dus|dur"t||}nt|}t| |||S )zhinge_embedding_loss(input, target, margin=1.0, size_average=None, reduce=None, reduction='mean') -> Tensor

    See :class:`~torch.nn.HingeEmbeddingLoss` for details.
    r  N)r   r   hinge_embedding_lossri  r  rj  r5   )r   rl  r  rm  ro  rf  r  r=   r=   r>   r  k  s   


r  c              	   C   ^   t | |rtt| |f| ||||dS |dus|dur!t||}nt|}tjj| ||S )zmultilabel_margin_loss(input, target, size_average=None, reduce=None, reduction='mean') -> Tensor

    See :class:`~torch.nn.MultiLabelMarginLoss` for details.
    r  N)	r   r   multilabel_margin_lossri  r  rj  r5   r7   r8   r   rl  rm  ro  rf  r  r=   r=   r>   r    s   
	
r  c              	   C   r  )z
    soft_margin_loss(input, target, size_average=None, reduce=None, reduction='mean') -> Tensor

    See :class:`~torch.nn.SoftMarginLoss` for details.
    r  N)	r   r   soft_margin_lossri  r  rj  r5   r7   r8   r  r=   r=   r>   r    s   
	
r  c           
   
   C   s   t | ||rtt| ||f| |||||dS |dus|dur#t||}|t|  d| t|     }|dur;|| }|  d }| |}|j|d| }|dkrV|}	|	S |dkr`|	 }	|	S |dkrj| }	|	S | }	t
|d )	zmultilabel_soft_margin_loss(input, target, weight=None, size_average=None, reduce=None, reduction='mean') -> Tensor

    See :class:`~torch.nn.MultiLabelSoftMarginLoss` for details.
    r  Nr)   r   rv  r(  r-  r{  )r   r   multilabel_soft_margin_lossri  rq  
logsigmoidr4   r3   r-  r(  r0   )
r   rl  r  rm  ro  rf  r  	class_dimCrp   r=   r=   r>   r    s<   
 
r  c                 C   sf   t | ||rtt| ||f| ||||||d	S |dus|dur%t||}nt|}t| ||||S )zcosine_embedding_loss(input1, input2, target, margin=0, size_average=None, reduce=None, reduction='mean') -> Tensor

    See :class:`~torch.nn.CosineEmbeddingLoss` for details.
    r  N)r   r   cosine_embedding_lossri  r  rj  r5   r  r=   r=   r>   r    s    
r  c           	      C   s   t | ||rtt| ||f| |||||||d
S |dus|dur&t||}nt|}|dkr7|dkr7td|durE| dkrEtdtj	j
| |||||S )zmulti_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.
    )r   r  r  rm  ro  rf  Nr)   r&   z only p == 1 and p == 2 supportedzweight must be one-dimensional)r   r   multi_margin_lossri  r  rj  r0   r4   r5   r7   r8   )	r   rl  r   r  r  rm  ro  rf  r  r=   r=   r>   r    s0   
r  a-  
pixel_shuffle(input, upscale_factor) -> Tensor

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)`, where r is the :attr:`upscale_factor`.

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])
at  
pixel_unshuffle(input, downscale_factor) -> Tensor

Reverses the :class:`~torch.nn.PixelShuffle` operation by rearranging elements in a
tensor of shape :math:`(*, C, H \times r, W \times r)` to a tensor of shape
:math:`(*, C \times r^2, H, W)`, where r is the :attr:`downscale_factor`.

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

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

Examples::

    >>> input = torch.randn(1, 1, 12, 12)
    >>> output = torch.nn.functional.pixel_unshuffle(input, 3)
    >>> print(output.size())
    torch.Size([1, 9, 4, 4])
a5  
channel_shuffle(input, groups) -> Tensor

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]],
     ]]
a  
native_channel_shuffle(input, groups) -> Tensor

Native kernel level implementation of the `channel_shuffle`.
This function might become private in future releases, use with caution.

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.native_channel_shuffle(input, 2)
    >>> print(output)
    [[[[1, 2],
       [3, 4]],
      [[9, 10],
       [11, 12]],
      [[5, 6],
       [7, 8]],
      [[13, 14],
       [15, 16]],
     ]]
nearestscale_factoralign_cornersc                 C      d S r  r=   r   r3   r  r*  r  r=   r=   r>   upsample     r  c                 C   r  r  r=   r  r=   r=   r>   r    r  c                 C   s   t jddd t| ||||S )a@  Upsample input.

    Provided tensor is upsampled 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:
        {backward_reproducibility_note}

    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 (str): 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.

    zP`nn.functional.upsample` is deprecated. Use `nn.functional.interpolate` instead.r&   r   r   r   interpolater  r=   r=   r>   r    s
   Ac                 C   s@   t | ttjfr
dS tdurt | tjrdS t | to|   S )zType check the input number is an integer.

    Will return True for int, SymInt, Numpy integers and Tensors with integer elements.
    TN)rw   r2   r5   SymIntnpintegerr   r0  )xr=   r=   r>   _is_integer%  s
   r  recompute_scale_factor	antialiasc                 C   r  r  r=   r   r3   r  r*  r  r  r  r=   r=   r>   r  1     
r  c                 C   r  r  r=   r  r=   r=   r>   r  >  r  c                 C   r  r  r=   r  r=   r=   r>   r  K  r  c                 C   r  r  r=   r  r=   r=   r>   r  X  r  c           	         s4  t  rtt f ||||d	S |dv r|durtdn|du r%d}  d }dur7dur7tddurdu sAJ dtttfrt|krbtdt j	dd  d	 d
t
j s|tdd D s|tddd D  }nJfddt|D }n>durňdu sJ d}tttfrt|krtdt j	dd  d dnfddt|D ntd|dur|r׈durtd|dkr|du rd}|dur)|r)dusJ t
j st
j r fddt|D }nt
j r fddt|D }n fddt|D }d|r;|dv r7 jdks;td  dkrP|d krPt
jj |S   dkre|d kret
jj |S   d!krz|d krzt
jj |S   dkr|d"krt
jj |S   dkr|d"krt
jj |S   d!kr|d"krt
jj |S   dkr|dkr|dusJ t |S   dkr|dkr|dusJ t |S   d!kr|dkr|dusJ t |S   dkr|d#kr|dusJ t
jj ||S   dkrf|d$krf|dus1J |r>t
jj ||S t
j s\t
 r\ j sQ j!r\t"#d%$ ||S t
jj% ||S   d!kr|d&kr|dusyJ t
jj& ||S   dkr|d'kr|dusJ |rt
jj' ||S t
jj( ||S   dkr|d$krt)d(  dkr|d&krt)d)  dkr|d#krt)d*  dkr|d&krt)d+  d!kr|d#krt)d,  d!kr|d$krt)d-t)d.   d/| d0)1a  Down/up samples the input.

    Tensor interpolated 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`, `nearest-exact`

    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. If `scale_factor` is a tuple,
            its length has to match the number of spatial dimensions; `input.dim() - 2`.
        mode (str): algorithm used for upsampling:
            ``'nearest'`` | ``'linear'`` | ``'bilinear'`` | ``'bicubic'`` |
            ``'trilinear'`` | ``'area'`` | ``'nearest-exact'``. 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. If `recompute_scale_factor` is ``True``, then
            `scale_factor` must be passed in and `scale_factor` is used to compute the
            output `size`. The computed output `size` will be used to infer new scales for
            the interpolation. Note that when `scale_factor` is floating-point, it may differ
            from the recomputed `scale_factor` due to rounding and precision issues.
            If `recompute_scale_factor` is ``False``, then `size` or `scale_factor` will
            be used directly for interpolation. Default: ``None``.
        antialias (bool, optional): flag to apply anti-aliasing. Default: ``False``. Using anti-alias
            option together with ``align_corners=False``, interpolation result would match Pillow
            result for downsampling operation. Supported modes: ``'bilinear'``, ``'bicubic'``.

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

    .. note::
        Mode ``mode='nearest-exact'`` matches Scikit-Image and PIL nearest neighbours interpolation
        algorithms and fixes known issues with ``mode='nearest'``. This mode is introduced to keep
        backward compatibility.
        Mode ``mode='nearest'`` matches buggy OpenCV's ``INTER_NEAREST`` interpolation algorithm.

    .. note::
        The gradients for the dtype ``float16`` on CUDA may be inaccurate in the upsample operation
        when using modes ``['linear', 'bilinear', 'bicubic', 'trilinear', 'area']``.
        For more details, please refer to the discussion in
        `issue#104157 <https://github.com/pytorch/pytorch/issues/104157>`_.

    Note:
        {backward_reproducibility_note}
    )r3   r  r*  r  r  r  )r  areanearest-exactNzjalign_corners option can only be set with the interpolating modes: linear | bilinear | bicubic | trilinearFr&   z2only one of size or scale_factor should be definedzkInput and output must have the same number of spatial dimensions, but got input with spatial dimensions of z and output size of zj. Please provide input tensor in (N, C, d1, d2, ...,dK) format and output size in (o1, o2, ...,oK) format.c                 s   s    | ]}t |V  qd S r  )r  .0r  r=   r=   r>   	<genexpr>  s    zinterpolate.<locals>.<genexpr>zqexpected size to be one of int or Tuple[int] or Tuple[int, int] or Tuple[int, int, int], but got size with types c                 S   s   g | ]}t |qS r=   )r7  r  r=   r=   r>   
<listcomp>  s    zinterpolate.<locals>.<listcomp>c                       g | ]} qS r=   r=   r  r=  )r3   r=   r>   r        zqInput and scale_factor must have the same number of spatial dimensions, but got input with spatial dimensions of z and scale_factor of shape zk. Please provide input tensor in (N, C, d1, d2, ...,dK) format and scale_factor in (s1, s2, ...,sK) format.c                    r  r=   r=   r  )r  r=   r>   r    r  z-either size or scale_factor should be definedz?recompute_scale_factor is not meaningful with an explicit size.r  Tc              	      s<   g | ]}t  |d   t j| t jd  qS )r&   r   )r5   floorr3   r~  tensorfloat32r  rA  r   scale_factorsr=   r>   r    s    	c              
      s0   g | ]}t tt |d  |  qS r&   )r2   r  r  r~  r3   r  r  r=   r>   r    s    "c                    s&   g | ]}t  |d  |  qS r  )_sym_intr3   r  r  r=   r>   r    s    )bilinearbicubicrD   z`Anti-alias option is restricted to bilinear and bicubic modes and requires a 4-D tensor as inputr*   r  r   r  linearr  torch._decomp.decompositions	trilinearr  z.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 z`D) for the modes: nearest | linear | bilinear | bicubic | trilinear | area | nearest-exact (got rj   )*r   r   r  r0   r4   rw   rX   tupler1   r1  r5   rV   r2  all	TypeErrorrk   r7   _get_tracing_stater   r8   upsample_nearest1dupsample_nearest2dupsample_nearest3d_upsample_nearest_exact1d_upsample_nearest_exact2d_upsample_nearest_exact3dadaptive_avg_pool1dr   r   upsample_linear1d_upsample_bilinear2d_aa$are_deterministic_algorithms_enabledis_cudais_xpu	importlibimport_module_upsample_linear_vecupsample_bilinear2dupsample_trilinear3d_upsample_bicubic2d_aaupsample_bicubic2dr:  )	r   r3   r  r*  r  r  r  r4   r    r=   )r   r  r  r3   r>   r  e  sJ  M
	



c                 C   r  r  r=   r   r3   r  r=   r=   r>   upsample_nearest     r  c                 C   r  r  r=   r  r=   r=   r>   r    r  c                 C   s   t jddd t| ||ddS )a|  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:
        {backward_reproducibility_note}
    zX`nn.functional.upsample_nearest` is deprecated. Use `nn.functional.interpolate` instead.r&   r   r  )r*  r  r  r=   r=   r>   r    s
   c                 C   r  r  r=   r  r=   r=   r>   upsample_bilinear  r  r  c                 C   r  r  r=   r  r=   r=   r>   r    r  c                 C   r  r  r=   r  r=   r=   r>   r    r  c                 C   r  r  r=   r  r=   r=   r>   r    r  c                 C   s    t jddd t| ||dddS )ah  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:
        {backward_reproducibility_note}
    zY`nn.functional.upsample_bilinear` is deprecated. Use `nn.functional.interpolate` instead.r&   r   r  T)r*  r  r  r  r=   r=   r>   r    s
   )r  r  r  )zerosborder
reflectionr  r   gridpadding_modec              	   C   s   t | |rtt| |f| ||||dS |dkr&|dkr&|dkr&td| d|dkr:|dkr:|d	kr:td
| d|dkrAd}n	|dkrHd}nd}|dkrQd}n	|dkrXd}nd}|du retd d}t| ||||S )a  Compute grid sample.

    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'`` | ``'bicubic'``. Default: ``'bilinear'``
            Note: ``mode='bicubic'`` supports only 4-D input.
            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`.

    .. note::
        ``mode='bicubic'`` is implemented using the `cubic convolution algorithm`_ with :math:`\alpha=-0.75`.
        The constant :math:`\alpha` might be different from packages to packages.
        For example, `PIL`_ and `OpenCV`_ use -0.5 and -0.75 respectively.
        This algorithm may "overshoot" the range of values it's interpolating.
        For example, it may produce negative values or values greater than 255 when interpolating input in [0, 255].
        Clamp the results with :func:`torch.clamp` to ensure they are within the valid range.
    .. _`cubic convolution algorithm`: https://en.wikipedia.org/wiki/Bicubic_interpolation
    .. _`PIL`: https://github.com/python-pillow/Pillow/blob/4634eafe3c695a014267eefdce830b4a825beed7/src/libImaging/Resample.c#L51
    .. _`OpenCV`: https://github.com/opencv/opencv/blob/f345ed564a06178670750bad59526cfa4033be55/modules/imgproc/src/resize.cpp#L908
    )r*  r  r  r  r  r  z_nn.functional.grid_sample(): expected mode to be 'bilinear', 'nearest' or 'bicubic', but got: 'rh   r   r  r  zgnn.functional.grid_sample(): expected padding_mode to be 'zeros', 'border', or 'reflection', but got: 'r   r)   r&   NDefault 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   grid_sampler0   r   r   r5   grid_sampler)r   r  r*  r  r  r<  padding_mode_enumr=   r=   r>   r    sL   
l	
r  thetac                 C   sR  t | rtt| f| ||dS |du rtd d}|  s%td| j t|dkrR| 	 dks?| j
d d	ks?| j
d
 dkrKtd| d| j
 d|dd }n5t|dkr| 	 dksl| j
d dksl| j
d
 dkrxtd| d| j
 d|dd }ntd| d|rt|dkrtd nt|dkrtd| t| ||S )av	  Generate 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).
    )r  Nr  Fz4Expected theta to have floating point type, but got rD   r*   r'   r&   r(   z?Expected a batch of 2D affine matrices of shape Nx2x3 for size z. Got .r   z?Expected a batch of 3D affine matrices of shape Nx3x4 for size r+   zcaffine_grid only supports 4D and 5D sizes, for 2D and 3D affine transforms, respectively. Got size r)   zSince 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   affine_gridr   r   r0  r0   r-   r1   r4   r1  r:  r|  r5   affine_grid_generator)r	  r3   r  spatial_sizer=   r=   r>   r    sJ   3
((r  constantr\  c                 C   sp   t | rttjjj| f| |||dS tj s.t r.| j	s!| j
r.|dkr.td| |S tjj| |||S )a
  
    pad(input, pad, mode="constant", value=None) -> Tensor

    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.CircularPad2d`, :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. Circular, replicate and
        reflection padding are implemented for padding the last 3 dimensions of a
        4D or 5D input tensor, the last 2 dimensions of a 3D or 4D input tensor,
        or the last dimension of a 2D or 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   	replicater  )r   r   r5   nn
functionalr\  rV   r2  r  r  r  r  r  _replication_padr7   r8   )r   r\  r*  r   r=   r=   r>   r\    s"   B
ztorch.nn.functionalzy
pairwise_distance(x1, x2, p=2.0, eps=1e-6, keepdim=False) -> Tensor

See :class:`torch.nn.PairwiseDistance` for details
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. ``x1`` and ``x2`` must be broadcastable
to a common shape. ``dim`` refers to the dimension in this common shape. Dimension ``dim`` of the output is
squeezed (see :func:`torch.squeeze`), resulting in the
output tensor having 1 fewer dimension.

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

Supports :ref:`type promotion <type-promotion-doc>`.

Args:
    x1 (Tensor): First input.
    x2 (Tensor): Second input.
    dim (int, optional): Dimension along which cosine similarity is computed. Default: 1
    eps (float, optional): Small value to avoid division by zero.
        Default: 1e-8

Example::

    >>> input1 = torch.randn(100, 128)
    >>> input2 = torch.randn(100, 128)
    >>> output = F.cosine_similarity(input1, input2)
    >>> print(output)
aw  
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, optional):  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. Default: -1

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]]])
anchorpositivenegativeswapc
                 C   s   t | ||rtt| ||f| |||||||||	dS |dus!|dur(t||}
nt|	}
|dkr8td| t| |||||||
S )zCompute the triplet loss between given input tensors and a margin greater than 0.

    See :class:`~torch.nn.TripletMarginLoss` for details.
    )r  r   r   r  rm  ro  rf  Nr   #margin must be greater than 0, got )r   r   triplet_margin_lossri  r  rj  r0   r5   )r  r  r  r  r   r   r  rm  ro  rf  r  r=   r=   r>   r    s.   
r  distance_functionr  r  rf  r  c                C   s   t j r	tdt| ||rtt| ||f| ||||||d	S |dvr*t| d|dkr5td| | j}|j}|j}	||krF||	ksTt	d| d| d	|	 d
|du r[t j
}|| |}
|| |}|rr|||}t ||}t ||
 | d}|dkrt |S |dkrt |S |S )zCompute the triplet margin loss for input tensors using a custom distance function.

    See :class:`~torch.nn.TripletMarginWithDistanceLoss` for details.
    zuF.triplet_margin_with_distance_loss does not support JIT scripting: functions requiring Callables cannot be scripted.r  )r(  r-  rv  rw  r   r  zoThe anchor, positive, and negative tensors are expected to have the same number of dimensions, but got: anchor zD, positive zD, and negative zD inputsNr-  r(  )r5   rV   r2  r:  r   r   !triplet_margin_with_distance_lossr0   r   r   pairwise_distanceminimum	clamp_minr-  r(  )r  r  r  r  r  r  rf  a_dimp_dimn_dimdist_posdist_neg	dist_swapr  r=   r=   r>   r    s\   





r  -q=r   c              	   C   s|   t | |rtt| |f| ||||dS |du r(| j||dd|| }| | S | j||dd|| }tj| ||dS )a\  Perform :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 or tuple of ints): 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   r4   r   r   NTr   )r   )	r   r   	normalizenormr  	expand_as
clamp_min_r5   r_  )r   r   r4   r   r   denomr=   r=   r>   r&  P  s   
r&  argrE   messagec                 C   s,   t | tst| dksJ ||d S d S )Nr&   )rw   r2   r1   format)r+  rE   r,  r=   r=   r>   assert_int_or_pairu  s   ,r.  c              	   C   sF   t | rtt| f| ||||dS tjj| t|t|t|t|S )a  Extract sliding local blocks from a 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
    rR   rQ   rP   )r   r   unfoldr5   r7   r8   im2colr   )r   r   rR   rQ   rP   r=   r=   r>   r0  y  s   	r0  c              
   C   sN   t | rtt| f| |||||dS tjj| t|t|t|t|t|S )zCombine an array of sliding local blocks into a large containing tensor.

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

    See :class:`torch.nn.Fold` for details
    r/  )r   r   foldr5   r7   r8   col2imr   )r   r    r   rR   rQ   rP   r=   r=   r>   r2    s&   
r2  qvwbc                 C   sL  |  d}||u rz| |u r2t| ||}|dd|fdddd }|d |d |d fS |||d g\}}|du rFd }	}
n|||d g\}	}
t| ||	}t|||
}|dd|fdddd }||d |d fS |d\}}}|du rd }	 }}n|d\}	}}t| ||	t|||t|||fS )aF  Perform the in-projection step of the attention operation, using packed weights.

    Output is a triple containing projection tensors for query, key and value.

    Args:
        q, k, v: query, key and value tensors to be projected. For self-attention,
            these are typically the same tensor; for encoder-decoder attention,
            k and v are typically the same tensor. (We take advantage of these
            identities for performance if they are present.) Regardless, q, k and v
            must share a common embedding dimension; otherwise their shapes may vary.
        w: projection weights for q, k and v, packed into a single tensor. Weights
            are packed along dimension 0, in q, k, v order.
        b: optional projection biases for q, k and v, packed into a single tensor
            in q, k, v order.

    Shape:
        Inputs:
        - q: :math:`(..., E)` where E is the embedding dimension
        - k: :math:`(..., E)` where E is the embedding dimension
        - v: :math:`(..., E)` where E is the embedding dimension
        - w: :math:`(E * 3, E)` where E is the embedding dimension
        - b: :math:`E * 3` where E is the embedding dimension

        Output:
        - in output list :math:`[q', k', v']`, each output tensor will have the
            same shape as the corresponding input tensor.
    r(   r*   r   r'   r)   r&   N)	r3   r  	unflattenry   	transposerz   r'  splitchunk)r4  rZ  r5  r6  r7  Eprojw_qw_kvb_qb_kvq_projkv_projw_kw_vb_kb_vr=   r=   r>   _in_projection_packed  s:   
"
"rH  r>  rD  rE  r@  rF  rG  c	                 C   s@  |  d| d| d}	}
}|j|	|	fks%J d|	|	f d|j |j|	|
fks9J d|	|
f d|j |j|	|fksMJ d|	|f d|j |du sc|j|	fkscJ d|	f d|j |du sy|j|	fksyJ d|	f d|j |du s|j|	fksJ d	|	f d|j t| ||t|||t|||fS )
a  Perform the in-projection step of the attention operation.

    This is simply a triple of linear projections,
    with shape constraints on the weights which
    ensure embedding dimension uniformity in the projected outputs.
    Output is a triple containing projection tensors for query, key and value.

    Args:
        q, k, v: query, key and value tensors to be projected.
        w_q, w_k, w_v: weights for q, k and v, respectively.
        b_q, b_k, b_v: optional biases for q, k and v, respectively.

    Shape:
        Inputs:
        - q: :math:`(Qdims..., Eq)` where Eq is the query embedding dimension and Qdims are any
            number of leading dimensions.
        - k: :math:`(Kdims..., Ek)` where Ek is the key embedding dimension and Kdims are any
            number of leading dimensions.
        - v: :math:`(Vdims..., Ev)` where Ev is the value embedding dimension and Vdims are any
            number of leading dimensions.
        - w_q: :math:`(Eq, Eq)`
        - w_k: :math:`(Eq, Ek)`
        - w_v: :math:`(Eq, Ev)`
        - b_q: :math:`(Eq)`
        - b_k: :math:`(Eq)`
        - b_v: :math:`(Eq)`

        Output: in output triple :math:`(q', k', v')`,
         - q': :math:`[Qdims..., Eq]`
         - k': :math:`[Kdims..., Eq]`
         - v': :math:`[Vdims..., Eq]`

    r(   z!expecting query weights shape of 
, but got zexpecting key weights shape of z!expecting value weights shape of Nzexpecting query bias shape of zexpecting key bias shape of zexpecting value bias shape of )r3   r1  r  )r4  rZ  r5  r>  rD  rE  r@  rF  rG  EqEkEvr=   r=   r>   _in_projection  sF   ","rM  ar  scaled_dot_product_attention(query, key, value, attn_mask=None, dropout_p=0.0,
        is_causal=False, scale=None, enable_gqa=False) -> Tensor:

    Computes scaled dot product attention on query, key and value tensors, using an optional attention mask if passed,
    and applying dropout if a probability greater than 0.0 is specified. The optional scale argument can only be
    specified as a keyword argument.

    .. code-block:: python

        # Efficient implementation equivalent to the following:
        def scaled_dot_product_attention(query, key, value, attn_mask=None, dropout_p=0.0,
                is_causal=False, scale=None, enable_gqa=False) -> torch.Tensor:
            L, S = query.size(-2), key.size(-2)
            scale_factor = 1 / math.sqrt(query.size(-1)) if scale is None else scale
            attn_bias = torch.zeros(L, S, dtype=query.dtype, device=query.device)
            if is_causal:
                assert attn_mask is None
                temp_mask = torch.ones(L, S, dtype=torch.bool).tril(diagonal=0)
                attn_bias.masked_fill_(temp_mask.logical_not(), float("-inf"))
                attn_bias.to(query.dtype)

            if attn_mask is not None:
                if attn_mask.dtype == torch.bool:
                    attn_bias.masked_fill_(attn_mask.logical_not(), float("-inf"))
                else:
                    attn_bias = attn_mask + attn_bias

            if enable_gqa:
                key = key.repeat_interleave(query.size(-3)//key.size(-3), -3)
                value = value.repeat_interleave(query.size(-3)//value.size(-3), -3)

            attn_weight = query @ key.transpose(-2, -1) * scale_factor
            attn_weight += attn_bias
            attn_weight = torch.softmax(attn_weight, dim=-1)
            attn_weight = torch.dropout(attn_weight, dropout_p, train=True)
            return attn_weight @ value

    .. warning::
        This function is beta and subject to change.

    .. warning::
        This function always applies dropout according to the specified ``dropout_p`` argument.
        To disable dropout during evaluation, be sure to pass a value of ``0.0`` when the module
        that makes the function call is not in training mode.

        For example:

        .. code-block:: python

            class MyModel(nn.Module):
                def __init__(self, p=0.5):
                    super().__init__()
                    self.p = p

                def forward(self, ...):
                    return F.scaled_dot_product_attention(...,
                        dropout_p=(self.p if self.training else 0.0))

    Note:

        There are currently three supported implementations of scaled dot product attention:

            - `FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning`_
            - `Memory-Efficient Attention`_
            - A PyTorch implementation defined in C++ matching the above formulation

        The function may call optimized kernels for improved performance when using the CUDA backend.
        For all other backends, the PyTorch implementation will be used.

        All implementations are enabled by default. Scaled dot product attention attempts to automatically select the
        most optimal implementation based on the inputs. In order to provide more fine-grained control over what implementation
        is used, the following functions are provided for enabling and disabling implementations.
        The context manager is the preferred mechanism:

            - :func:`torch.nn.attention.sdpa_kernel`: A context manager used to enable or disable any of the implementations.
            - :func:`torch.backends.cuda.enable_flash_sdp`: Globally enables or disables FlashAttention.
            - :func:`torch.backends.cuda.enable_mem_efficient_sdp`: Globally enables or disables  Memory-Efficient Attention.
            - :func:`torch.backends.cuda.enable_math_sdp`: Globally enables or disables  the PyTorch C++ implementation.

        Each of the fused kernels has specific input limitations. If the user requires the use of a specific fused implementation,
        disable the PyTorch C++ implementation using :func:`torch.nn.attention.sdpa_kernel`.
        In the event that a fused implementation is not available, a warning will be raised with the
        reasons why the fused implementation cannot run.

        Due to the nature of fusing floating point operations, the output of this function may be different
        depending on what backend kernel is chosen.
        The c++ implementation supports torch.float64 and can be used when higher precision is required.
        For math backend, all intermediates are kept in torch.float if inputs are in torch.half or torch.bfloat16.
    For more information please see :doc:`/notes/numerical_accuracy`

        Grouped Query Attention (GQA) is an experimental feature. It currently works only for Flash_attention
        and math kernel on CUDA tensor, and does not support Nested tensor.
        Constraints for GQA:

            - number_of_heads_query % number_of_heads_key_value == 0 and,
            - number_of_heads_key == number_of_heads_value

    Note:

        {cudnn_reproducibility_note}
    a^  
    Args:
        query (Tensor): Query tensor; shape :math:`(N, ..., Hq, L, E)`.
        key (Tensor): Key tensor; shape :math:`(N, ..., H, S, E)`.
        value (Tensor): Value tensor; shape :math:`(N, ..., H, S, Ev)`.
        attn_mask (optional Tensor): Attention mask; shape must be broadcastable to the shape of attention weights,
            which is :math:`(N,..., L, S)`. Two types of masks are supported.
            A boolean mask where a value of True indicates that the element *should* take part in attention.
            A float mask of the same type as query, key, value that is added to the attention score.
        dropout_p (float): Dropout probability; if greater than 0.0, dropout is applied
        is_causal (bool): If set to true, the attention masking is a lower triangular matrix when the mask is a
            square matrix. The attention masking has the form of the upper left causal bias due to the alignment
            (see :class:`torch.nn.attention.bias.CausalBias`) when the mask is a non-square matrix.
            An error is thrown if both attn_mask and is_causal are set.
        scale (optional float, keyword-only): Scaling factor applied prior to softmax. If None, the default value is set
            to :math:`\frac{1}{\sqrt{E}}`.
        enable_gqa (bool): If set to True, Grouped Query Attention (GQA) is enabled, by default it is set to False.

    Returns:
        output (Tensor): Attention output; shape :math:`(N, ..., Hq, L, Ev)`.

    Shape legend:
        - :math:`N: \text{Batch size} ... : \text{Any number of other batch dimensions (optional)}`
        - :math:`S: \text{Source sequence length}`
        - :math:`L: \text{Target sequence length}`
        - :math:`E: \text{Embedding dimension of the query and key}`
        - :math:`Ev: \text{Embedding dimension of the value}`
        - :math:`Hq: \text{Number of heads of query}`
        - :math:`H: \text{Number of heads of key and value}`

    Examples:

        >>> # Optionally use the context manager to ensure one of the fused kernels is run
        >>> query = torch.rand(32, 8, 128, 64, dtype=torch.float16, device="cuda")
        >>> key = torch.rand(32, 8, 128, 64, dtype=torch.float16, device="cuda")
        >>> value = torch.rand(32, 8, 128, 64, dtype=torch.float16, device="cuda")
        >>> with sdpa_kernel(backends=[SDPBackend.FLASH_ATTENTION]):
        >>>     F.scaled_dot_product_attention(query,key,value)


        >>> # Sample for GQA for llama3
        >>> query = torch.rand(32, 32, 128, 64, dtype=torch.float16, device="cuda")
        >>> key = torch.rand(32, 8, 128, 64, dtype=torch.float16, device="cuda")
        >>> value = torch.rand(32, 8, 128, 64, dtype=torch.float16, device="cuda")
        >>> with sdpa_kernel(backends=[SDPBackend.MATH]):
        >>>     F.scaled_dot_product_attention(query,key,value,enable_gqa=True)


    .. _FlashAttention-2\: Faster Attention with Better Parallelism and Work Partitioning:
        https://arxiv.org/abs/2307.08691
    .. _Memory-Efficient Attention:
        https://github.com/facebookresearch/xformers
    .. _Grouped-Query Attention:
        https://arxiv.org/pdf/2305.13245
    querykeykey_padding_mask	attn_mask	num_headsc                 C   s  |   dkrMd}|  dkr|  dks#J d|   d|   d|d ur7|  dks7J d|   d|d urK|  d	v sKJ d
|   d|S |   dkrd}|  dkra|  dkspJ d|   d|   d|d ur|  dksJ d|   d|d ur|  d	v sJ d|   d|  dkr|| jd |jd f}|j|ksJ d| d|j |S td|    d)Nr*   TzJFor batched (3-D) `query`, expected `key` and `value` to be 3-D but found z-D and z-D tensors respectivelyr&   zUFor batched (3-D) `query`, expected `key_padding_mask` to be `None` or 2-D but found z-D tensor insteadr   zSFor batched (3-D) `query`, expected `attn_mask` to be `None`, 2-D or 3-D but found FzLFor unbatched (2-D) `query`, expected `key` and `value` to be 2-D but found r)   zWFor unbatched (2-D) `query`, expected `key_padding_mask` to be `None` or 1-D but found zUFor unbatched (2-D) `query`, expected `attn_mask` to be `None`, 2-D or 3-D but found r   z!Expected `attn_mask` shape to be z	 but got z?query should be unbatched 2D or batched 3D tensor but received z-D query tensor)r4   r1  AssertionError)rN  rO  r   rP  rQ  rR  r   expected_shaper=   r=   r>   _mha_shape_check  sh   !rU  mask	mask_name
other_type
other_nametarget_typecheck_otherc                 C   s   | d ur@| j }t| }|tjkr|std| d|r1|d ur1||kr1td| d| d |s@tj| |d| t	d} | S )Nz only bool and floating types of z are supportedzSupport for mismatched ri   z/ is deprecated. Use same type for both instead.r   z-inf)
r-   r5   r0  boolrS  r   r   r  masked_fill_r~  )rV  rW  rX  rY  rZ  r[  _mask_dtype_mask_is_floatr=   r=   r>   _canonical_mask9  s"   

r`  c                 C   s&   | d u rd S t | tjr| jS td)Nz6input to _none_or_dtype() must be None or torch.Tensor)rw   r5   r   r-   r   r   r=   r=   r>   _none_or_dtypeU  s
   ra  src_lenbszc                    sH   t tjd  k fdd t tjd kfdd d S )Nr   c                      s   d  dj d  S )Nz(Expected key_padded_mask.shape[0] to be rI  r   r1  r=   )rc  rP  r=   r>   <lambda>c      z)_check_key_padding_mask.<locals>.<lambda>r)   c                      s   d d j d  S )Nz(Expected key_padded_mask.shape[1] to be rI  r)   rd  r=   )rP  rb  r=   r>   re  h  rf  )r5   _check_withrS  r1  )rP  rb  rc  r=   )rc  rP  rb  r>   _check_key_padding_mask]  s   rh  embed_dim_to_checkin_proj_weightin_proj_biasbias_kbias_vadd_zero_attn	dropout_pout_proj_weightout_proj_biasneed_weightsuse_separate_proj_weightq_proj_weightk_proj_weightv_proj_weightstatic_kstatic_vaverage_attn_weights	is_causalc           0      C   s(  | ||||||||f	}t |r0tt|| |||||||||	|
||f||||||||||||dS t| |||||}|sS| d} |d}|d}|durS|d}| j\}}}|j\}}}t|dt|d| jd}|ru|du rut	d|r|du r|sd}nt|ddd	| jd
d}|durd
}||ksJ d| d| t
|tjr|j|dd} n|| } | | |ksJ d| d| |r|jdd |jdd ksJ d|jdd  d|jdd  n|j|jksJ d|j d|j |s|dusJ dt| ||||\}!}"}#n>|dusJ d|dus"J d|dus+J d|du r7d }$ }%}&n|d\}$}%}&t| ||||||$|%|&	\}!}"}#|dur| dkrv||f}'|j|'krpt	d|j d|' d|d}n+| dkr|| ||f}(|j|(krt	d|j d|( dn
t	d |  d!|dur|dur|du sJ d"|du sJ d#t|"|d|dg}"t|#|d|dg}#|durt|d$}|durt|d$}n|du sJ |du sJ |!||| | dd}!|du r|"|"jd || | dd}"n0|d|| ks4J d%||  d|d |d| ksIJ d&|  d|d |}"|du ra|#|#jd || | dd}#n0|d|| kszJ d'||  d|d |d| ksJ d(|  d|d |}#|	r|| d| f})tj|"tj|)|"j|"jd)gdd*}"tj|#tj|)|#j|#jd)gdd*}#|durt|d$}|durt|d$}|"d}|durtj stj st||| ||dd|d+|d+d+|| d|}|du r
|}n|| }|sd,}
|r|!j\}*}+},|!t !d-t"|,  }-|r3|du r3J d.|durDt#||-|"d/d+}.n
t$|-|"d/d+}.t%|.d+d*}.|
d,kr_t&|.|
d0}.t$|.|#}/|/dd' || |}/t(|/||}/|/|||/d}/|.||||}.|r|.j)dd*}.|s|/*d}/|.*d}.|/|.fS |dur|ddkr| dkr|d}n|||d+|}|!|||| }!|"|||| }"|#|||| }#t+|!|"|#||
|}/|/,dddd' || |}/t(|/||}/|/|||/d}/|s|/*d}/|/dfS )1a  Forward method for MultiHeadAttention.

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

    See :class:`torch.nn.MultiheadAttention` for details.

    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.
            Default: `True`
            Note: `needs_weight` defaults to `True`, but should be set to `False`
            For best performance when attention weights are not needed.
            *Setting needs_weights to `True`
            leads to a significant performance degradation.*
        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.
        is_causal: If specified, applies a causal mask as attention mask, and ignores
            attn_mask for computing scaled dot product attention.
            Default: ``False``.
            .. warning::
                is_causal is provides a hint that the attn_mask is the
                causal mask.Providing incorrect hints can result in
                incorrect execution, including forward and backward
                compatibility.
        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.
        average_attn_weights: If true, indicates that the returned ``attn_weights`` should be averaged across heads.
            Otherwise, ``attn_weights`` are provided separately per head. Note that this flag only has an effect
            when ``need_weights=True.``. Default: True


    Shape:
        Inputs:
        - query: :math:`(L, E)` or :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is
          the embedding dimension.
        - key: :math:`(S, E)` or :math:`(S, N, E)`, where S is the source sequence length, N is the batch size, E is
          the embedding dimension.
        - value: :math:`(S, E)` or :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:`(S)` or :math:`(N, S)` where N is the batch size, S is the source sequence length.
          If a FloatTensor is provided, it will be directly added to the value.
          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 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, E)` or :math:`(L, N, E)` where L is the target sequence length, N is the batch size,
          E is the embedding dimension.
        - attn_output_weights: Only returned when ``need_weights=True``. If ``average_attn_weights=True``, returns
          attention weights averaged across heads of shape :math:`(L, S)` when input is unbatched or
          :math:`(N, L, S)`, where :math:`N` is the batch size, :math:`L` is the target sequence length, and
          :math:`S` is the source sequence length. If ``average_attn_weights=False``, returns attention weights per
          head of shape :math:`(num_heads, L, S)` when input is unbatched or :math:`(N, num_heads, L, S)`.
    )r   rP  rr  rQ  rz  rs  rt  ru  rv  rw  rx  ry  r)   Nr   rP  rQ  )rV  rW  rX  rY  rZ  zNeed attn_mask if specifying the is_causal hint. You may use the Transformer module method `generate_square_subsequent_mask` to create this mask. F)rV  rW  rX  rY  rZ  r[  z%was expecting embedding dimension of rI  trunc)rounding_modez
embed_dim z not divisible by num_heads r&   zkey's sequence and batch dims z do not match value's z
key shape z does not match value shape z<use_separate_proj_weight is False but in_proj_weight is Nonez:use_separate_proj_weight is True but q_proj_weight is Nonez:use_separate_proj_weight is True but k_proj_weight is Nonez:use_separate_proj_weight is True but v_proj_weight is Noner*   z!The shape of the 2D attn_mask is z, but should be r
  z!The shape of the 3D attn_mask is zattn_mask's dimension z is not supportedz#bias cannot be added to static key.z%bias cannot be added to static value.)r   r)   zexpecting static_k.size(0) of zexpecting static_k.size(2) of zexpecting static_v.size(0) of zexpecting static_v.size(2) of r,   r   r(   r   r   z1FIXME: is_causal not implemented for need_weightsr'   )r   )-r   r   multi_head_attention_forwardrU  ry   r1  r`  ra  r-   r   rw   r5   r   r_  rH  r;  rM  r4   catrepeatr\  r]  r9  r3   r   r.   rV   r2  
is_tracingrh  r  r5  r  sqrtr~  baddbmmbmmr   r   r'  r  r(  rz   scaled_dot_product_attentionpermute)0rN  rO  r   ri  rR  rj  rk  rl  rm  rn  ro  rp  rq  r   rP  rr  rQ  rs  rt  ru  rv  rw  rx  ry  rz  tens_opsr   tgt_lenrc  	embed_dimrb  r=  head_dimr4  rZ  r5  r@  rF  rG  correct_2d_sizecorrect_3d_sizezero_attn_shape_B_Ntr<  q_scaledattn_output_weightsattn_outputr=   r=   r>   r~  l  s  n



	
"







"
"












r~  r=   )NNFN)Nr   r)   FF)Nr   N)NF)F)r   TF)r   FF)r(   )r   r   F)r   F)r   F)r   r   FF)Nr*   N)r)   Fr   r(   )NNr"  FF)	NNr&   Fr(  FNFN)NNFrC  rD  )NNNNTrC  rD  )NNrD  )NN)rW  rX  r   )r   r(  F)NNrk  Nr(  )TFNrs  Nr(  )Fry  r(  )NNr(  F)NNrk  Nr(  r   )NNNr(  )NNNr(  N)NNr(  r   )r(  r   N)NNr(  N)r   NNr(  )r   NNr(  )NNr(  )r)   r   NNNr(  )NNr  N)NNr  NNF)r  r   Nr  )r  N)r   r&   ry  FNNr(  )r"  r)   r%  N)r)   r   r)   )NNN)T)TNTNFNNNNNTF)__doc__r  r  r   typingr   r   r   r   r5   r   r   r  r   torch._Cr	   r
   torch._jit_internalr   r   r   r   r   torch._torch_docsr   r   r   torch.nnr   ri  r   torch.nn.modules.utilsr   r   r   r   torch.overridesr   r   r   r   torch.typesr   DTyper2   numpyr  ModuleNotFoundErrorconv1dr-  conv2dconv3dconv_transpose1dconv_transpose2dconv_transpose3dconv_tbcr   r7   r8   r   r   r~  r\  r  r/   rB   __name__r9   rM   rO   rN   rU   r]   r\   ra   rd   rc   re   rg   rf   rX   rs   rv   rx   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   r   r   r   r   r   r   r   r   r   r   r   r   r   prelur   r   log_sigmoidr  gelu
hardshrinkr   r   softplusr6  r   r   r   r  r  
softshrinkr   r  r  r  r  r  r  r  r!  r&  r.  rB  rJ  rN  rP  rS  rT  rV  r[  rh  rp  rx  r}  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  pixel_shufflepixel_unshufflechannel_shufflenative_channel_shuffler  r  r  r  r  GRID_SAMPLE_INTERPOLATION_MODESGRID_SAMPLE_PADDING_MODESr  r  r\  
__module__r  pdistcosine_similarityone_hotr  r  r&  r.  r0  r2  rH  rM  r  rU  r`  ra  rh  r~  r=   r=   r=   r>   <module>   s   354+-," 



P






T





8




8




8



)


+


%


%


*


(


'




 


!



5
=
6
/









	
#
-
L
"



x	

 W	
,	
.


)2KH	G
^V	gGO3S>O(! 3#	**.

I




  





 #iU
 6	
/
	O(%*.R	
Edeg $D	
