/usr/local/lib64/python3.6/site-packages/torch/nn/__pycache__
NameSizeModeActions
common_types.cpython-36.pyc9900644editdlrm
cpp.cpython-36.pyc34600644editdlrm
functional.cpython-36.pyc1616480644editdlrm
grad.cpython-36.pyc118400644editdlrm
init.cpython-36.pyc175510644editdlrm
parameter.cpython-36.pyc75680644editdlrm
_reduction.cpython-36.pyc12440644editdlrm
__init__.cpython-36.pyc20020644editdlrm
Edit: /usr/local/lib64/python3.6/site-packages/torch/nn/__pycache__/functional.cpython-36.pyc (161648B)
3 Eg#@sddZddlmZmZmZmZddlZddlZddlZddlm Z ddl m Z m Z ddl mZmZddlmZmZmZmZmZdd lmZmZmZmZd d lmZd d lmZd d lm Z d dl!m"Z"m#Z#m$Z$m%Z%ej&Z&e ej'dj(feedZ'e ej)dj(feedZ)e ej*dj(feedZ*e ej+dj(feedZ+e ej,dj(feedZ,e ej-dj(feedZ-e ej.dZ.e ej/dZ/e ej0j1j2dZ2e ej0j1j3dZ3dse&ee4eee4eee5e6ee&ee&e&fd d!d"Z7dte&ee4eee4eee5e6ee&e&d d#d$Z8ed%d&de7e8e9d'd(Z:due&ee4eee4eee5e6ee&ee&e&fd d)d*Z;dve&ee4eee4eee5e6ee&e&d d+d,Zdxe&ee4eee4ee4ee4e6e6e&d.d1d2Z?ed%d3de>e?e9d4d(Z@dye&ee4eee4ee4ee4e6e6ee&e&fd.d5d6ZAdze&ee4eee4ee4ee4e6e6e&d.d7d8ZBed%d3deAeBe9d9d(ZCd{e&ee4eee4ee4ee4e6e6ee&e&fd.d:d;ZDd|e&ee4eee4ee4ee4e6e6e&d.dd(ZFe&ee4ee4ee4eee4ee4d?d@dAZGd}e&e&ee4eee4ee4eee4e&dBdCdDZHd~e&e&ee4eee4ee4eee4e&dBdEdFZIde&e&ee4eee4ee4eee4e&dBdGdHZJde&e5e4eee4e6e&dIdJdKZKde&e5e4eee4e6e&dIdLdMZLde&ee4e6ee&e&fdNdOdPZMde&ee4e6e&dNdQdRZNed%ddeMeNe9dSd(ZOde&ee4e6ee&e&fdNdTdUZPde&ee4e6e&dNdVdWZQed%ddePeQe9dXd(ZRde&ee4e6ee&e&fdNdYdZZSde&ee4e6e&dNd[d\ZTed%ddeSeTe9d]d(ZUe ejVd^ZVe&ee4e&d_d`daZWe&ee4e&d_dbdcZXde&e5e6e6e&dfdgdhZYde&e5e6e6e&dfdidjZZde&e5e6e6e&dfdkdlZ[de&e5e6e6e&dfdmdnZ\de&e5e6e6e&dfdodpZ]de&e5e5e6e&dqdrdsZ^e^Z_e e j`dtZ`de&e6e&dudvdwZae ejbdxZbde&e4e&dydzd{Zcde&e5e5e6e&d}d~dZde ej0j1jedZede&e6e&duddZfde&e5e6e&dddZge ej0j1jhdZhde&e6e&duddZie ejjdZjde&e5e6e&dddZke ejldZlde&e5e6e&dddZme ej0j1jndZne&e&e&dddZode&e5e5e6e6e&dddZpe ejqdZqe ej0j1jrdZsddZtde&e5e&dddZuddZvddZwe ej0j1jxdZxeye4e4e4dddZzde&ee4e4ee4e&dddZ{de&ee4e4ee4e&dddZ|de&e5e6e5e4e&dddZ}de&ee4e4ee4e&dddZ~e ej0j1jdZddZddZde&e6e&duddZde&e&ee&e&dddZde&e&e&ee&e&dddZde&e6e&dudd„Zde&e6e&duddĄZde&e6e&duddƄZe&e&e5e5e&dǜddɄZde&e&ee4ee5e5e6e6e&d˜dd̈́Zde&e&ee&ee5e5e6eye6ee&e6ee4e&dϜ ddфZejj(fee_ee4ddҜddԄZde&ee&ee&ee&ee&e6e5e5e&dל ddلZee4ddҜddۄZde&ee&ee&ee&ee&e6e5e5e&dܜ ddބZde&ee4ee&ee&e5e&dߜddZde&e4ee&ee&e5e&dddZde&e4e5e5e5e&dddZde&e&e&e&e4eye6e&dddZejj(fee_de&e&ee&ee6e4ee6eye&dddZde&e&e6e6ee6e5ee6eye&d ddZde&e&e&e6e5eye&dddZde&e&ee6ee6eye6e&dddZde&e&ee&ee6e4ee6eye5e&d ddZde&e&ee&ee6ee6eye&dddZde&e&ee&ee6ee6eyee&e&dddZde&e&ee6ee6eye5e&dddZde&e&eye5e&d d d Zde&e&ee6ee6eye&d d dZde&e&ee6ee6eye&d ddZde&e&e&e5ee6ee6eye&dddZde&e&e5ee6ee6eye&dddZde&e&ee6ee6eye&d ddZde&e&ee6ee6eye&d ddZde&e&ee&ee6ee6eye&dddZde&e&e&e5ee6ee6eye&dddZde&e&e4e5ee&ee6ee6eye&d d d!Ze ejd"Ze ejd#Ze ejd$Zede&ee4ee5eyee6e&d&d'd(Zede&eee4ee5eyee6e&d&d)d(ZdŐd*d(Zejj(fee_ede&ee4eee5eyee6ee6e&d+d,d-Zede&eee4eee5eyee6ee6e&d+d.d-Zede&ee4ee5eyee6ee6e&d+d/d-Zede&eee4ee5eyee6ee6e&d+d0d-Zde&ee4eee5eyee6ee6e&d+d1d-Zejj(fee_ede&ee4ee5e&d2d3d4Zede&eee4ee5e&d2d5d4Zd͐d6d4Zejj(fee_ede&ee4ee5e&d2d7d8Zede&eee4ee5e&d2d9d8Zede&ee4eee5e&d2d:d8Zede&eee4eee5e&d2d;d8ZdҐd<d8Zejj(fee_dd dd=Zdd dd>Zde&e&eyeyee6e&d@dAdBZde&ee4ee6e&dCdDdEZde&ee4eye5e&dGdHdIZeZde&e&e5e5e6e&dJdKdLZe ejdMZe ejdNZe ej0j1jdOZde&e&e&e5e5e5e6ee6ee6eye&dP dQdRZdd|ddΐdSe&e&e&eee&e&ge&fe5e6eye&dTdUdVZde&e5e4e5ee&e&dXdYdZZee4eyeydd[d\d]Zde&ee4ee4ee4ee4e&d^d_d`Zde&ee4ee4ee4ee4ee4e&dadbdcZe&ee4e&dddedfZde&e&e&e&ee&ee&dgdhdiZde&e&e&e&e&e&ee&ee&ee&ee&e&e&fdj dkdlZde&e&e&ee&e5ee&e&fdmdndoZde&e&e&e4e4e&ee&ee&ee&e6e5e&ee&e6ee&e6ee&e6ee&ee&ee&ee&ee&ee&ee&fdpdqdrZdS(zFunctional interface)CallableListOptionalTupleN)_VF) _infer_size _add_docstr)reproducibility_notes tf32_notes)boolean_dispatch _overloadBroadcastingList1BroadcastingList2BroadcastingList3)has_torch_functionhas_torch_function_unaryhas_torch_function_variadichandle_torch_function) _reduction)grad)utils)_single_pair_triple_list_with_defaulta 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} ad 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 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) a 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} 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 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, :math:`\text{in\_channels}` should be divisible by the number of groups. Default: 1 Examples:: >>> # With square kernels and equal stride >>> filters = torch.randn(8, 4, 3, 3) >>> inputs = torch.randn(1, 4, 5, 5) >>> F.conv2d(inputs, filters, padding=1) a 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} 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 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_ratioreturn_indices_random_samplesreturnc Cst||r&tt||f||||||dS|dkr>|dkr>td|dkr|dk sRtt|}t|jd |dt|jd |dg}|dkr|jdkrdn|jd}t j ||jd d|j |j d}t j jj||||S) abApplies 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 )rr r!r"NzRfractional_max_pool2d requires specifying either an output_size or an output_ratior rr)dtypedevice)rr"fractional_max_pool2d_with_indices ValueErrorAssertionErrorrintsizedimtorchrandr%r&_C_nnfractional_max_pool2d)rrrr r!r" _output_ratioZn_batchr6?/usr/local/lib64/python3.6/site-packages/torch/nn/functional.pyr*s($  ,r*c Cs<t||r&tt||f||||||dSt||||||dS)N)rr r!r"r)rrr4r*)rrrr r!r"r6r6r7_fractional_max_pool2ds r8r!r4)arg_nameZ arg_indexdefaultif_trueif_false module_name func_namec Cst||r&tt||f||||||dS|dkr>|dkr>td|dkr|dk sRtt|}t|jd|dt|jd|dt|jd|dg}|dkrtj |jd|jdd|j |j d }tj j j||||S) aApplies 3D fractional max pooling over an input signal composed of several input planes. Fractional MaxPooling is described in detail in the paper `Fractional MaxPooling`_ by Ben Graham The max-pooling operation is applied in :math:`kT \times kH \times kW` regions by a stochastic step size determined by the target output size. The number of output features is equal to the number of input planes. Args: kernel_size: the size of the window to take a max over. Can be a single number :math:`k` (for a square kernel of :math:`k \times k \times k`) or a tuple `(kT, kH, kW)` output_size: the target output size of the form :math:`oT \times oH \times oW`. Can be a tuple `(oT, oH, oW)` or a single number :math:`oH` for a cubic output :math:`oH \times oH \times oH` output_ratio: If one wants to have an output size as a ratio of the input size, this option can be given. This has to be a number or tuple in the range (0, 1) return_indices: if ``True``, will return the indices along with the outputs. Useful to pass to :func:`~torch.nn.functional.max_unpool3d`. Examples:: >>> input = torch.randn(20, 16, 50, 32, 16) >>> # pool of cubic window of size=3, and target output size 13x12x11 >>> F.fractional_max_pool3d(input, 3, output_size=(13, 12, 11)) >>> # pool of cubic window and target output size being half of input size >>> F.fractional_max_pool3d(input, 3, output_ratio=(0.5, 0.5, 0.5)) .. _Fractional MaxPooling: http://arxiv.org/abs/1412.6071 )rr r!r"NzRfractional_max_pool3d requires specifying either an output_size or an output_ratior rr$rr9)r%r&)rr"fractional_max_pool3d_with_indicesr+r,rr-r.r0r1r%r&r2r3fractional_max_pool3d)rrrr r!r"r5r6r6r7r@s*%  $r@c Cs<t||r&tt||f||||||dSt||||||dS)N)rr r!r"r)rrrAr@)rrrr r!r"r6r6r7_fractional_max_pool3d7s rBrA)rrstridepaddingdilation ceil_moder!r#c CsRt|r$tt|f|||||||d S|dkr>tjjttg}tj||||||S)zApplies a 1D max pooling over an input signal composed of several input planes. See :class:`~torch.nn.MaxPool1d` for details. )rCrDrErFr!N)rrmax_pool1d_with_indicesr0jitannotaterr-)rrrCrDrErFr!r6r6r7rGYs rGc CsRt|r$tt|f|||||||d S|dkr>tjjttg}tj||||||S)N)rCrDrErFr!)rr max_pool1dr0rHrIrr-)rrrCrDrErFr!r6r6r7 _max_pool1dwsrKrJc CsVt|r$tt|f|||||||d S|dkr>tjjttg}tjj j||||||S)zApplies a 2D max pooling over an input signal composed of several input planes. See :class:`~torch.nn.MaxPool2d` for details. )rCrDrErFr!N) rrmax_pool2d_with_indicesr0rHrIrr-r2r3)rrrCrDrErFr!r6r6r7rMs rMc CsRt|r$tt|f|||||||d S|dkr>tjjttg}tj||||||S)N)rCrDrErFr!)rr max_pool2dr0rHrIrr-)rrrCrDrErFr!r6r6r7 _max_pool2dsrOrNc CsVt|r$tt|f|||||||d S|dkr>tjjttg}tjj j||||||S)zApplies a 3D max pooling over an input signal composed of several input planes. See :class:`~torch.nn.MaxPool3d` for details. )rCrDrErFr!N) rrmax_pool3d_with_indicesr0rHrIrr-r2r3)rrrCrDrErFr!r6r6r7rPs rPc CsRt|r$tt|f|||||||d S|dkr>tjjttg}tj||||||S)N)rCrDrErFr!)rr max_pool3dr0rHrIrr-)rrrCrDrErFr!r6r6r7 _max_pool3dsrRrQ)rrrCrDrr#c Cs8|j}tjjttg}xLtt|D]<}|j|t| |d||||d||q(W|dkrv|}nt|t|dkr|dd}t|t|krt dj t|t|dt|xftt|D]V}||||} ||||} | ||ko| knst dj ||| | qW|}|S)Nrr zZoutput_size should be a sequence containing {} or {} elements, but it has a length of '{}'z;invalid output_size "{}" (dim {} must be between {} and {})) r.r0rHrIrr-rangelenappendr+format) rrrCrDrZ input_sizeZ default_sizedretZmin_sizemax_sizer6r6r7_unpool_output_sizes*< rZ)rindicesrrCrDrr#c Cst|r"tt|f||||||dSt|}|dk r 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) )rrr#cCs6t|rtt|f||St||j}tjjj||S)a" Applies a 2D adaptive average pooling over an input signal composed of several input planes. See :class:`~torch.nn.AdaptiveAvgPool2d` for details and output shape. Args: output_size: the target output size (single integer or double-integer tuple) )rradaptive_avg_pool2drr.r0r2r3)rr _output_sizer6r6r7ry]s rycCs6t|rtt|f||St||j}tjjj||S)a" Applies a 3D adaptive average pooling over an input signal composed of several input planes. See :class:`~torch.nn.AdaptiveAvgPool3d` for details and output shape. Args: output_size: the target output size (single integer or triple-integer tuple) )rradaptive_avg_pool3drr.r0r2r3)rrrzr6r6r7r{ns r{?T)rptraininginplacer#cCs\t|rtt|f||||dS|dks.|dkr Tensor In-place version of :func:`~threshold`. )rrr#cCs8t|rtt|f||dS|r*tj|}n tj|}|S)zrelu(input, inplace=False) -> Tensor Applies the rectified linear unit function element-wise. See :class:`~torch.nn.ReLU` for more details. )r)rrrir0relu_)rrrr6r6r7ris   riz< relu_(input) -> Tensor In-place version of :func:`~relu`. )rr/r#cCs>t|rtt|f||dS|jdkr.tdtjjj||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 `_. Args: input (Tensor): input tensor dim (int): dimension on which to split the input. Default: -1 )r/rz>glu does not support scalars because halving size must be even)rrglur/ RuntimeErrorr0r2r3)rr/r6r6r7r!s  r?)rmin_valmax_valrr#cCsLt|rtt|f||||dS|r6tjjj|||}ntjjj|||}|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. )rrr)rrhardtanhr0r2r3 hardtanh_)rrrrrr6r6r7r:s rz] hardtanh_(input, min_val=-1., max_val=1.) -> Tensor In-place version of :func:`~hardtanh`. cCs@t|rtt|f||dS|r.tjjj|}ntjjj|}|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)rrrelu6r0r2r3Zrelu6_)rrrr6r6r7rTs r)ralpharr#cCsFt|rtt|f|||dS|r2tjjj||}ntjjj||}|S)zApplies element-wise, :math:`\text{ELU}(x) = \max(0,x) + \min(0, \alpha * (\exp(x) - 1))`. See :class:`~torch.nn.ELU` for more details. )rr)rrelur0r2r3elu_)rrrrr6r6r7rds rzD elu_(input, alpha=1.) -> Tensor In-place version of :func:`~elu`. cCs8t|rtt|f||dS|r*tj|}n tj|}|S)a>selu(input, inplace=False) -> Tensor Applies element-wise, :math:`\text{SELU}(x) = scale * (\max(0,x) + \min(0, \alpha * (\exp(x) - 1)))`, with :math:`\alpha=1.6732632423543772848170429916717` and :math:`scale=1.0507009873554804934193349852946`. See :class:`~torch.nn.SELU` for more details. )r)rrselur0selu_)rrrr6r6r7r}s   rz< selu_(input) -> Tensor In-place version of :func:`~selu`. cCs>t|rtt|f|||dS|r.tj||}n tj||}|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. )rr)rrcelur0celu_)rrrrr6r6r7rs  rzF celu_(input, alpha=1.) -> Tensor In-place version of :func:`~celu`. {Gz?)rnegative_sloperr#cCsFt|rtt|f|||dS|r2tjjj||}ntjjj||}|S)z leaky_relu(input, negative_slope=0.01, inplace=False) -> Tensor Applies element-wise, :math:`\text{LeakyReLU}(x) = \max(0, x) + \text{negative\_slope} * \min(0, x)` See :class:`~torch.nn.LeakyReLU` for more details. )rr)rr leaky_relur0r2r3 leaky_relu_)rrrrr6r6r7rs rz] leaky_relu_(input, negative_slope=0.01) -> Tensor In-place version of :func:`~leaky_relu`. )rweightr#cCs$t|rtt|f||Stj||S)zprelu(input, weight) -> Tensor Applies element-wise the function :math:`\text{PReLU}(x) = \max(0,x) + \text{weight} * \min(0,x)` where weight is a learnable parameter. See :class:`~torch.nn.PReLU` for more details. )rrprelur0)rrr6r6r7rs rr$)rlowerupperr~rr#c CsJt|r tt|f|||||dS|r6tj||||}ntj||||}|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. )rrr~r)rrrrelur0rrelu_)rrrr~rrr6r6r7rs rzf 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. cCs$t|rtt|f|Stjjj|S)agelu(input) -> Tensor Applies element-wise the function :math:`\text{GELU}(x) = x * \Phi(x)` where :math:`\Phi(x)` is the Cumulative Distribution Function for Gaussian Distribution. See `Gaussian Error Linear Units (GELUs) `_. )rrgelur0r2r3)rr6r6r7rs r)rlambdr#cCs&t|rtt|f||dStj||S)z hardshrink(input, lambd=0.5) -> Tensor Applies the hard shrinkage function element-wise See :class:`~torch.nn.Hardshrink` for more details. )r)rr hardshrinkr0)rrr6r6r7rsrcCs"t|rtt|f|S||jS)ztanhshrink(input) -> Tensor Applies element-wise, :math:`\text{Tanhshrink}(x) = x - \text{Tanh}(x)` See :class:`~torch.nn.Tanhshrink` for more details. )rr tanhshrinktanh)rr6r6r7r$srcCs&t|rtt|f|S||jdS)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)rrsoftsignrj)rr6r6r7r0sraJ 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. )namendim stacklevelr#cCs:tjdj||d|dks,|dks,|dkr2d}nd}|S)NzfImplicit dimension choice for {} has been deprecated. Change the call to include dim=X as an argument.)rrrr$)warningswarnrV)rrrrXr6r6r7_get_softmax_dimKsr)rr/ _stacklevelr%r#cCs`t|rtt|f||||dS|dkr6td|j|}|dkrL| j|}n| j||d}|S)avApplies 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. )r/rr%Nsoftmin)r%)rrrrr/softmax)rr/rr%rXr6r6r7rXsrcCs\t|rtt|f||||dS|dkr6td|j|}|dkrJ|j|}n|j||d}|S)aApplies 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/rr%Nr)r%)rrrrr/)rr/rr%rXr6r6r7rrs r绽|=)logitstauhardepsr/r#c Cst|r tt|f|||||dS|dkr2tjdtj|tjdjj }|||}|j |}|r|j |ddd}tj |tjdj ||d}||j|} n|} | S) a Samples from the Gumbel-Softmax distribution (`Link 1`_ `Link 2`_) and optionally discretizes. Args: logits: `[..., num_features]` unnormalized log probabilities tau: non-negative scalar temperature hard: if ``True``, the returned samples will be discretized as one-hot vectors, but will be differentiated as if it is the soft sample in autograd dim (int): A dimension along which softmax will be computed. Default: -1. Returns: Sampled tensor of same shape as `logits` from the Gumbel-Softmax distribution. If ``hard=True``, the returned samples will be one-hot, otherwise they will be probability distributions that sum to 1 across `dim`. .. note:: This function is here for legacy reasons, may be removed from nn.Functional in the future. .. note:: The main trick for `hard` is to do `y_hard - y_soft.detach() + y_soft` It achieves two things: - makes the output value exactly one-hot (since we add then subtract y_soft value) - makes the gradient equal to y_soft gradient (since we strip all other gradients) Examples:: >>> logits = torch.randn(20, 32) >>> # Sample soft categorical using reparametrization trick: >>> F.gumbel_softmax(logits, tau=1, hard=False) >>> # Sample hard categorical using "Straight-through" trick: >>> F.gumbel_softmax(logits, tau=1, hard=True) .. _Link 1: https://arxiv.org/abs/1611.00712 .. _Link 2: https://arxiv.org/abs/1611.01144 )rrrr/g|=z0`eps` parameter is deprecated and has no effect.)Z memory_formatT)keepdimrg?)rrgumbel_softmaxrrr0Z empty_likeZlegacy_contiguous_formatZ exponential_logrmax zeros_likeZscatter_detach) rrrrr/ZgumbelsZy_softindexZy_hardrXr6r6r7rs(   rcCs\t|rtt|f||||dS|dkr6td|j|}|dkrJ|j|}n|j||d}|S)aApplies 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/rr%N log_softmax)r%)rrrrr/)rr/rr%rXr6r6r7rs rz softshrink(input, lambd=0.5) -> Tensor Applies the soft shrinkage function elementwise See :class:`~torch.nn.Softshrink` for more details. cCstjd|jS)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. z9nn.functional.tanh is deprecated. Use torch.tanh instead.)rrr)rr6r6r7rs rcCstjd|jS)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. z?nn.functional.sigmoid is deprecated. Use torch.sigmoid instead.)rrsigmoid)rr6r6r7rs rcCs:t|rtt|f||dS|r,tjjj|Stjjj|S)aApplies the element-wise function .. math:: \text{Hardsigmoid}(x) = \begin{cases} 0 & \text{if~} x \le -3, \\ 1 & \text{if~} x \ge +3, \\ x / 6 + 1 / 2 & \text{otherwise} \end{cases} Args: inplace: If set to ``True``, will do this operation in-place. Default: ``False`` See :class:`~torch.nn.Hardsigmoid` for more details. )r)rr hardsigmoidr0r2r3Z hardsigmoid_)rrr6r6r7rs r)rrbiasr#cCs6t|||r$tt|||f|||dStjjj|||S)a Applies a linear transformation to the incoming data: :math:`y = xA^T + b`. This operator supports :ref:`TensorFloat32`. Shape: - Input: :math:`(N, *, in\_features)` N is the batch size, `*` means any number of additional dimensions - Weight: :math:`(out\_features, in\_features)` - Bias: :math:`(out\_features)` - Output: :math:`(N, *, out\_features)` )r)rrlinearr0r2r3)rrrr6r6r7r(s r)input1input2rrr#cCs:t||||r*tt||||f||||dStj||||S)a Applies a bilinear transformation to the incoming data: :math:`y = x_1^T A x_2 + b` Shape: - input1: :math:`(N, *, H_{in1})` where :math:`H_{in1}=\text{in1\_features}` and :math:`*` means any number of additional dimensions. All but the last dimension of the inputs should be the same. - input2: :math:`(N, *, H_{in2})` where :math:`H_{in2}=\text{in2\_features}` - weight: :math:`(\text{out\_features}, \text{in1\_features}, \text{in2\_features})` - bias: :math:`(\text{out\_features})` - output: :math:`(N, *, H_{out})` where :math:`H_{out}=\text{out\_features}` and all but the last dimension are the same shape as the input. )r)rrbilinearr0)rrrrr6r6r7r;s rcCs:t|rtt|f||dS|r,tjjj|Stjjj|S)aApplies 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) `_ where the SiLU (Sigmoid Linear Unit) was originally coined, and see `Sigmoid-Weighted Linear Units for Neural Network Function Approximation in Reinforcement Learning `_ and `Swish: a Self-Gated Activation Function `_ where the SiLU was experimented with later. See :class:`~torch.nn.SiLU` for more details. )r)rrsilur0r2r3Zsilu_)rrr6r6r7rVs rcCs:t|rtt|f||dS|r,tjjj|Stjjj|S)avApplies 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 `_ See :class:`~torch.nn.Mish` for more details. )r)rrmishr0r2r3Zmish_)rrr6r6r7rns rcCs:t|rtt|f||dS|r,tjjj|Stjjj|S)aApplies the hardswish function, element-wise, as described in the paper: `Searching for MobileNetV3`_. .. math:: \text{Hardswish}(x) = \begin{cases} 0 & \text{if~} x \le -3, \\ x & \text{if~} x \ge +3, \\ x \cdot (x + 3) /6 & \text{otherwise} \end{cases} See :class:`~torch.nn.Hardswish` for more details. .. _`Searching for MobileNetV3`: https://arxiv.org/abs/1905.02244 )r)rr hardswishr0r2r3Z hardswish_)rrr6r6r7rs r)rrmax_normrdr#c Cs(tjtj||||WdQRXdS)N)r0no_gradZembedding_renorm_)rrrrdr6r6r7_no_grad_embedding_renorm_s r@)rr padding_idxrrdscale_grad_by_freqsparser#c Cst||r&tt||f||||||| S|dk r~|dkrN||jdks|tdq|dkr||jd ksntd|jd|}nd}|dk r|j}t||||tj|||||S)as A simple lookup table that looks up embeddings in a fixed dictionary and size. This module is often used to retrieve word embeddings using indices. The input to the module is a list of indices, and the embedding matrix, and the output is the corresponding word embeddings. See :class:`torch.nn.Embedding` for more details. Args: input (LongTensor): Tensor containing indices into the embedding matrix weight (Tensor): The embedding matrix with number of rows equal to the maximum possible index + 1, and number of columns equal to the embedding size padding_idx (int, optional): If 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 (boolean, optional): If given, this will scale gradients by the inverse of frequency of the words in the mini-batch. Default ``False``. sparse (bool, optional): If ``True``, gradient w.r.t. :attr:`weight` will be a sparse tensor. See Notes under :class:`torch.nn.Embedding` for more details regarding sparse gradients. Shape: - Input: LongTensor of arbitrary shape containing the indices to extract - Weight: Embedding matrix of floating point type with shape `(V, embedding_dim)`, where V = maximum index + 1 and embedding_dim = the embedding size - Output: `(*, embedding_dim)`, where `*` is the input shape Examples:: >>> # a batch of 2 samples of 4 indices each >>> input = torch.tensor([[1,2,4,5],[4,3,2,9]]) >>> # an embedding matrix containing 10 tensors of size 3 >>> embedding_matrix = torch.rand(10, 3) >>> F.embedding(input, embedding_matrix) tensor([[[ 0.8490, 0.9625, 0.6753], [ 0.9666, 0.7761, 0.6108], [ 0.6246, 0.9751, 0.3618], [ 0.4161, 0.2419, 0.7383]], [[ 0.6246, 0.9751, 0.3618], [ 0.0237, 0.7794, 0.0528], [ 0.9666, 0.7761, 0.6108], [ 0.3385, 0.8612, 0.1867]]]) >>> # example with padding_idx >>> weights = torch.rand(10, 3) >>> weights[0, :].zero_() >>> embedding_matrix = weights >>> input = torch.tensor([[0,2,0,5]]) >>> F.embedding(input, embedding_matrix, padding_idx=0) tensor([[[ 0.0000, 0.0000, 0.0000], [ 0.5609, 0.5384, 0.8720], [ 0.0000, 0.0000, 0.0000], [ 0.6262, 0.2438, 0.7471]]]) Nrz)Padding_idx must be within num_embeddingsrr()rr embeddingr.r, contiguousrr0)rrrrrdrrr6r6r7rs D  rmean) rroffsetsrrdrmoderper_sample_weightsinclude_last_offsetrr#c Cs t||||r8tt||||f|||||||||| | d S|jtjkr`|jr`tjd||}}|dk r|j |j krt dj |j |j |j dkr |dk rd} tjjstt|} t dj | tjd|j|j d |j|jd }|jd}|dk rV|jd}nJ|j d krD|dkr,t d |j d krVt d nt d j |j |dkrfd} nD|dkrvd } n4|dkrd} |rt d|rt dnt d|dk rt|||||dk r|dkrtdj |tj||||| ||| | \} }}}| S)aComputes sums, means or maxes of `bags` of embeddings, 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 (boolean, optional): if given, this will scale gradients by the inverse of frequency of the words in the mini-batch. Default ``False``. Note: this option is not supported when ``mode="max"``. mode (string, optional): ``"sum"``, ``"mean"`` or ``"max"``. Specifies the way to reduce the bag. Default: ``"mean"`` sparse (bool, optional): if ``True``, gradient w.r.t. :attr:`weight` will be a sparse tensor. See Notes under :class:`torch.nn.Embedding` for more details regarding sparse gradients. Note: this option is not supported when ``mode="max"``. per_sample_weights (Tensor, optional): a tensor of float / double weights, or None to indicate all weights should be taken to be 1. If specified, :attr:`per_sample_weights` must have exactly the same shape as input and is treated as having the same :attr:`offsets`, if those are not None. include_last_offset (bool, optional): if ``True``, the size of offsets is equal to the number of bags + 1. The last element is the size of the input, or the ending index position of the last bag (sequence). 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]) >>> 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]]) ) rrrdrrrrrrzArgument order of nn.functional.embedding_bag was changed. Usage `embedding_bag(weight, input, ...)` is deprecated, and should now be `embedding_bag(input, weight, ...)`.Nziembedding_bag: If per_sample_weights ({}) is not None, then it must have the same shape as the input ({})r z 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 {}rr)r%r&z*offsets has to be a 1D Tensor but got Nonezoffsets has to be a 1D Tensorz?input has to be 1D or 2D Tensor, but got Tensor of dimension {}sumrrz?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 maxzembedding_bag: per_sample_weights was not None. per_sample_weights is only supported for mode='sum' (got mode='{}'). Please open a feature request on GitHub.r(r()rr embedding_bagr%r0longis_floating_pointrrr.r+rVshaper/rH is_scriptingstrtypeZarangenumelr&reshaperNotImplementedError)rrrrrdrrrrrrZtype_str mode_enumrX_r6r6r7rsz[    "          r)r.r#cCsL|d}x(tt|dD]}|||d9}qW|dkrHtdj|dS)Nrr rzGExpected more than 1 value per channel when training, got input size {})rSrTr+rV)r. size_prodsir6r6r7_verify_batch_sizes r皙?h㈵>) r running_mean running_varrrr~momentumrr#c Csft|||||r6tt|||||f||||||||d S|rFt|jtj||||||||tjjj S)zApplies 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. )rrr~rr) rr batch_normrr.r0backendscudnnenabled)rrrrrr~rrr6r6r7rs   rcCsBd}x"tdt|D]}|||9}qW|dkr>tdj|dS)Nrr zEExpected more than 1 spatial element when training, got input size {})rSrTr+rV)r.rrr6r6r7_verify_spatial_sizes r) rrrrruse_input_statsrrr#c Csft|||||r6tt|||||f||||||||d S|rFt|jtj||||||||tjjj S)zApplies Instance Normalization for each channel in each data sample in a batch. See :class:`~torch.nn.InstanceNorm1d`, :class:`~torch.nn.InstanceNorm2d`, :class:`~torch.nn.InstanceNorm3d` for details. )rrrrrrr) rr instance_normrr.r0rrr)rrrrrrrrr6r6r7rs   r)rnormalized_shaperrrr#c CsBt|||r(tt|||f|||||dStj|||||tjjjS)zzApplies Layer Normalization for last certain number of dimensions. See :class:`~torch.nn.LayerNorm` for details. )rrr)rr layer_normr0rrr)rrrrrr6r6r7r s r)r num_groupsrrrr#c Csvt|||r(tt|||f|||||dSt|jd|jd||gt|jddtj|||||tjjj S)zzApplies Group Normalization for last certain number of dimensions. See :class:`~torch.nn.GroupNorm` for details. )rrrrrr N) rr group_normrr.r^r0rrr)rrrrrr6r6r7r. s 4r-C6??)rr.rbetakr#c Cs(t|r tt|f|||||dS|j}|dkr>tdj||jdkrN|S|j|jd}|dkrt |dd|d|ddf}t ||dfddj d}nl|j }|j |dd|d|dd}t |dddd|d|ddf}t||ddfddj d}|j |}|j|j|j|}||S) zApplies local response normalization over an input signal composed of several input planes, where channels occupy the second dimension. Applies normalization across channels. See :class:`~torch.nn.LocalResponseNorm` for details. )rrrr$zWExpected 3D or higher dimensionality input (got {} dimensions)rrr )rCr()rrlocal_response_normr/r+rVrrkr`padrfrar.view avg_pool3daddrg)rr.rrrr/divsizesr6r6r7r; s( " r) log_probstargets input_lengthstarget_lengthsblank reduction zero_infinityr#c CsLt||||r0tt||||f|||||||d Stj|||||tj||S)aThe 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)` where `C = number of characters in alphabet including blank`, `T = input length`, and `N = batch size`. The logarithmized probabilities of the outputs (e.g. obtained with :func:`torch.nn.functional.log_softmax`). targets: :math:`(N, S)` or `(sum(target_lengths))`. Targets cannot be blank. In the second form, the targets are assumed to be concatenated. input_lengths: :math:`(N)`. Lengths of the inputs (must each be :math:`\leq T`) target_lengths: :math:`(N)`. Lengths of the targets blank (int, optional): Blank label. Default :math:`0`. reduction (string, optional): Specifies the reduction to apply to the output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied, ``'mean'``: the output losses will be divided by the target lengths and then the mean over the batch is taken, ``'sum'``: the output will be summed. Default: ``'mean'`` zero_infinity (bool, optional): Whether to zero infinite losses and the associated gradients. Default: ``False`` Infinite losses mainly occur when the inputs are too short to be aligned to the targets. Example:: >>> log_probs = torch.randn(50, 16, 20).log_softmax(2).detach().requires_grad_() >>> targets = torch.randint(1, 20, (16, 30), dtype=torch.long) >>> input_lengths = torch.full((16,), 50, dtype=torch.long) >>> target_lengths = torch.randint(10,30,(16,), dtype=torch.long) >>> loss = F.ctc_loss(log_probs, targets, input_lengths, target_lengths) >>> loss.backward() )r r r )rrctc_lossr0 _Reductionget_enum)rrrr r r r r6r6r7r a s4  r d)rtargetr size_average ignore_indexreducer r#c Csdt|||r,tt|||f|||||||d S|dk s<|dk rHtj||}tjjj|||tj ||S)a The negative log likelihood loss. See :class:`~torch.nn.NLLLoss` for details. Args: input: :math:`(N, C)` where `C = number of classes` or :math:`(N, C, H, W)` in case of 2D Loss, or :math:`(N, C, d_1, d_2, ..., d_K)` where :math:`K \geq 1` in the case of K-dimensional loss. `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 (string, optional): Specifies the reduction to apply to the output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied, ``'mean'``: the sum of the output will be divided by the number of elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average` and :attr:`reduce` are in the process of being deprecated, and in the meantime, specifying either of those two args will override :attr:`reduction`. Default: ``'mean'`` Example:: >>> # input is of size N x C = 3 x 5 >>> input = torch.randn(3, 5, requires_grad=True) >>> # each element in target has to have 0 <= value < C >>> target = torch.tensor([1, 0, 4]) >>> output = F.nll_loss(F.log_softmax(input), target) >>> output.backward() )rrrrr N) rrnll_lossrlegacy_get_stringr0r2r3Z nll_loss_ndr)rrrrrrr r6r6r7r s2  r:0yE>) rr log_inputfullrrrr r#c Cst||r*tt||f||||||||d S|dk s:|dk rFtj||}|dkrn|dkrn|dkrn|}t|dtj|||||tj|}|S)aPoisson negative log likelihood loss. See :class:`~torch.nn.PoissonNLLLoss` for details. Args: input: expectation of underlying Poisson distribution. target: random sample :math:`target \sim \text{Poisson}(input)`. log_input: if ``True`` the loss is computed as :math:`\exp(\text{input}) - \text{target} * \text{input}`, if ``False`` then loss is :math:`\text{input} - \text{target} * \log(\text{input}+\text{eps})`. Default: ``True`` full: whether to compute full loss, i. e. to add the Stirling approximation term. Default: ``False`` :math:`\text{target} * \log(\text{target}) - \text{target} + 0.5 * \log(2 * \pi * \text{target})`. size_average (bool, optional): Deprecated (see :attr:`reduction`). By default, the losses are averaged over each loss element in the batch. Note that for some losses, there multiple elements per sample. If the field :attr:`size_average` is set to ``False``, the losses are instead summed for each minibatch. Ignored when reduce is ``False``. Default: ``True`` eps (float, optional): Small value to avoid evaluation of :math:`\log(0)` when :attr:`log_input`\ =\ ``False``. Default: 1e-8 reduce (bool, optional): Deprecated (see :attr:`reduction`). By default, the losses are averaged or summed over observations for each minibatch depending on :attr:`size_average`. When :attr:`reduce` is ``False``, returns a loss per batch element instead and ignores :attr:`size_average`. Default: ``True`` reduction (string, optional): Specifies the reduction to apply to the output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied, ``'mean'``: the sum of the output will be divided by the number of elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average` and :attr:`reduce` are in the process of being deprecated, and in the meantime, specifying either of those two args will override :attr:`reduction`. Default: ``'mean'`` )rrrrrr Nnonerrz is not valid)rrpoisson_nll_lossrrr+r0r) rrrrrrrr rXr6r6r7r s&*   rư>)rrvarrrr r#c Csbt|||r*tt|||f||||||dS|j|jkr|jdd|jkr`tj|d}n8|jdd|jddkr|jddkrntd|dkr|dkr|dkrt|dtj|d krtd |j}tj |j |d WdQRXd tj |||d |}|r6|d t j d t j 7}|dkrH|jS|dkrZ|jS|SdS)aGaussian 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). 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 (string, 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'``. )rrr Nrzvar is of incorrect sizerrrz is not validrzvar has negative entry/entries)ming?r r(r(r(r(r()rrgaussian_nll_lossr.r0r`r+anyclonerZclamp_rmathpirr)rrrrrr lossr6r6r7r( s> .    r)rrrrr  log_targetr#c Cst||r&tt||f||||||dS|dk s6|dk rDtj||}n0|dkrVtjd|dkrjtjd}n tj|}tj||||d}|dkr|j dkr||j d}|S) a0 The `Kullback-Leibler divergence Loss `__ 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 (string, optional): Specifies the reduction to apply to the output: ``'none'`` | ``'batchmean'`` | ``'sum'`` | ``'mean'``. ``'none'``: no reduction will be applied ``'batchmean'``: the sum of the output will be divided by the batchsize ``'sum'``: the output will be summed ``'mean'``: the output will be divided by the number of elements in the output Default: ``'mean'`` log_target (bool): A flag indicating whether ``target`` is passed in the log space. It is recommended to pass certain distributions (like ``softmax``) in the log space to avoid numerical issues caused by explicit ``log``. Default: ``False`` .. note:: :attr:`size_average` and :attr:`reduce` are in the process of being deprecated, and in the meantime, specifying either of those two args will override :attr:`reduction`. .. note:: :attr:`reduction` = ``'mean'`` doesn't return the true kl divergence value, please use :attr:`reduction` = ``'batchmean'`` which aligns with KL math definition. In the next major release, ``'mean'`` will be changed to be the same as 'batchmean'. )rrr r%Nrzreduction: 'mean' divides the total loss by both the batch size and the support size.'batchmean' divides only by the batch size, and aligns with the KL div math definition.'mean' will be changed to behave the same as 'batchmean' in the next major release.Z batchmeanr)r%r) rrkl_divrlegacy_get_enumrrrr0r/r.)rrrrr r%reduction_enumZreducedr6r6r7r&} s,/   r&) rrrrrrr label_smoothingr#c Csht|||r.tt|||f||||||||d S|dk s>|dk rJtj||}tjjj|||tj |||S)a This criterion computes the cross entropy loss between input and target. See :class:`~torch.nn.CrossEntropyLoss` for details. Args: input (Tensor) : :math:`(N, C)` where `C = number of classes` or :math:`(N, C, H, W)` in case of 2D Loss, or :math:`(N, C, d_1, d_2, ..., d_K)` where :math:`K \geq 1` in the case of K-dimensional loss. `input` is expected to contain unnormalized scores (often referred to as logits). target (Tensor) : If containing class indices, shape :math:`(N)` where each value is :math:`0 \leq \text{targets}[i] \leq C-1`, or :math:`(N, d_1, d_2, ..., d_K)` with :math:`K \geq 1` in the case of K-dimensional loss. If containing class probabilities, same shape as the input. 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 (string, optional): Specifies the reduction to apply to the output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied, ``'mean'``: the sum of the output will be divided by the number of elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average` and :attr:`reduce` are in the process of being deprecated, and in the meantime, specifying either of those two args will override :attr:`reduction`. Default: ``'mean'`` 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 `__. Default: :math:`0.0`. 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() )rrrrr r*N) rr cross_entropyrrr0r2r3Zcross_entropy_lossr)rrrrrrr r*r6r6r7r+ s@  r+)rrrrrr r#c Cst|||r*tt|||f||||||dS|dk s:|dk rHtj||}n tj|}|j|jkrztdj|j|j|dk rt |j|j}|j |}t j j j||||S)aFunction that measures the 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 (string, optional): Specifies the reduction to apply to the output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied, ``'mean'``: the sum of the output will be divided by the number of elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average` and :attr:`reduce` are in the process of being deprecated, and in the meantime, specifying either of those two args will override :attr:`reduction`. Default: ``'mean'`` Examples:: >>> input = torch.randn((3, 2), requires_grad=True) >>> target = torch.rand((3, 2), requires_grad=False) >>> loss = F.binary_cross_entropy(F.sigmoid(input), target) >>> loss.backward() )rrrr NzwUsing a target size ({}) that is different to the input size ({}) is deprecated. Please ensure they have the same size.)rrbinary_cross_entropyrr'rr.r+rVrexpandr0r2r3)rrrrrr r(Znew_sizer6r6r7r,! s*)   r,)rrrrrr  pos_weightr#c Cst||||r0tt||||f|||||||d S|dk s@|dk rNtj||}n tj|}|j|jkstdj|j|jt j|||||S)aZFunction that measures 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 (string, optional): Specifies the reduction to apply to the output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied, ``'mean'``: the sum of the output will be divided by the number of elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average` and :attr:`reduce` are in the process of being deprecated, and in the meantime, specifying either of those two args will override :attr:`reduction`. Default: ``'mean'`` pos_weight (Tensor, optional): a weight of positive examples. Must be a vector with length equal to the number of classes. Examples:: >>> input = torch.randn(3, requires_grad=True) >>> target = torch.empty(3).random_(2) >>> loss = F.binary_cross_entropy_with_logits(input, target) >>> loss.backward() )rrrr r.Nz4Target size ({}) must be the same as input size ({})) rr binary_cross_entropy_with_logitsrr'rr.r+rVr0)rrrrrr r.r(r6r6r7r/f s",  r/)rrrrr rr#c Cst||r&tt||f||||||dS|j|jksTtjdj|j|jdd|dk sd|dk rptj||}t j ||\}}t j j j||tj ||S)zFunction that uses a squared term if the absolute element-wise error falls below beta and an L1 term otherwise. See :class:`~torch.nn.SmoothL1Loss` for details. )rrr rzUsing a target size ({}) that is different to the input size ({}). This will likely lead to incorrect results due to broadcasting. Please ensure they have the same size.r )rN)rrsmooth_l1_lossr.rrrVrrr0broadcast_tensorsr2r3r)rrrrr rexpanded_inputexpanded_targetr6r6r7r0 s&  r0)rrr deltar#cCszt||r"tt||f||||dS|j|jksPtjdj|j|jddtj||\}}tj j j||t j ||S)zFunction that uses a squared term if the absolute element-wise error falls below delta and a delta-scaled L1 term otherwise. See :class:`~torch.nn.HuberLoss` for details. )r r4zUsing a target size ({}) that is different to the input size ({}). This will likely lead to incorrect results due to broadcasting. Please ensure they have the same size.r )r) rr huber_lossr.rrrVr0r1r2r3rr)rrr r4r2r3r6r6r7r5 s r5)rrrrr r#c Cst||r$tt||f|||||dS|j|jksRtjdj|j|jdd|dk sb|dk rntj||}t j ||\}}t j j j||tj |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. )rrr zUsing a target size ({}) that is different to the input size ({}). This will likely lead to incorrect results due to broadcasting. Please ensure they have the same size.r )rN)rrl1_lossr.rrrVrrr0r1r2r3r)rrrrr r2r3r6r6r7r6 s  r6c Cst||r$tt||f|||||dS|j|jksRtjdj|j|jdd|dk sb|dk rntj||}t j ||\}}t j j j||tj |S)zmse_loss(input, target, size_average=None, reduce=None, reduction='mean') -> Tensor Measures the element-wise mean squared error. See :class:`~torch.nn.MSELoss` for details. )rrr zUsing a target size ({}) that is different to the input size ({}). This will likely lead to incorrect results due to broadcasting. Please ensure they have the same size.r )rN)rrmse_lossr.rrrVrrr0r1r2r3r)rrrrr r2r3r6r6r7r7 s  r7)rrrmarginrrr r#c Cst|||r,tt|||f|||||||d S|dk s<|dk rJtj||}n tj|}|jdksx|jdksx|jdkrtdj|j |j |j t j|||||S)zmargin_ranking_loss(input1, input2, target, margin=0, size_average=None, reduce=None, reduction='mean') -> Tensor See :class:`~torch.nn.MarginRankingLoss` for details. )r8rrr Nrz\margin_ranking_loss does not support scalars, got sizes: input1: {}, input2: {}, target: {} ) rrmargin_ranking_lossrr'rr/rrVr.r0)rrrr8rrr r(r6r6r7r9+ s&  $r9)rrr8rrr r#c Cs^t||r&tt||f||||||dS|dk s6|dk rDtj||}n tj|}tj||||S)zhinge_embedding_loss(input, target, margin=1.0, size_average=None, reduce=None, reduction='mean') -> Tensor See :class:`~torch.nn.HingeEmbeddingLoss` for details. )r8rrr N)rrhinge_embedding_lossrr'rr0)rrr8rrr r(r6r6r7r:R s  r:c Cs^t||r$tt||f|||||dS|dk s4|dk rBtj||}n tj|}tjjj|||S)zmultilabel_margin_loss(input, target, size_average=None, reduce=None, reduction='mean') -> Tensor See :class:`~torch.nn.MultiLabelMarginLoss` for details. )rrr N) rrmultilabel_margin_lossrr'rr0r2r3)rrrrr r(r6r6r7r;p s  r;c Cs^t||r$tt||f|||||dS|dk s4|dk rBtj||}n tj|}tjjj|||S)zsoft_margin_loss(input, target, size_average=None, reduce=None, reduction='mean') -> Tensor See :class:`~torch.nn.SoftMarginLoss` for details. )rrr N) rrsoft_margin_lossrr'rr0r2r3)rrrrr r(r6r6r7r< s  r<c Cst|||r*tt|||f||||||dS|dk s:|dk rFtj||}|t|d|t|  }|dk rv||}|jdd|jd}|dkr|}n4|dkr|j}n"|dkr|j}n|}t |d|S) zmultilabel_soft_margin_loss(input, target, weight=None, size_average=None) -> Tensor See :class:`~torch.nn.MultiLabelSoftMarginLoss` for details. )rrrr Nr)r/rrrz is not valid) rrmultilabel_soft_margin_lossrr logsigmoidrr.rr+)rrrrrr r$rXr6r6r7r= s2      r=c Csft|||r,tt|||f|||||||d S|dk s<|dk rJtj||}n tj|}tj|||||S)zcosine_embedding_loss(input1, input2, target, margin=0, size_average=None, reduce=None, reduction='mean') -> Tensor See :class:`~torch.nn.CosineEmbeddingLoss` for details. )r8rrr N)rrcosine_embedding_lossrr'rr0)rrrr8rrr r(r6r6r7r? s  r?) rrr}r8rrrr r#c Cst|||r.tt|||f||||||||d S|dk s>|dk rLtj||}n tj|}|dkrn|dkrntd|dk r|jdkrtdtj 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}r8rrrr Nrr z only p == 1 and p == 2 supportedzweight must be one-dimensional) rrmulti_margin_lossrr'rr+r/r0r2r3) rrr}r8rrrr r(r6r6r7r@ s*   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]], ]] nearest)rr. scale_factorr align_cornersr#cCsdS)Nr6)rr.rBrrCr6r6r7upsampler srDcCsdS)Nr6)rr.rBrrCr6r6r7rDw scCstjdt|||||S)a% Upsamples the input to either the given :attr:`size` or the given :attr:`scale_factor` .. warning:: This function is deprecated in favor of :func:`torch.nn.functional.interpolate`. This is equivalent with ``nn.functional.interpolate(...)``. Note: {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 (string): algorithm used for upsampling: ``'nearest'`` | ``'linear'`` | ``'bilinear'`` | ``'bicubic'`` | ``'trilinear'``. Default: ``'nearest'`` align_corners (bool, optional): Geometrically, we consider the pixels of the input and output as squares rather than points. If set to ``True``, the input and output tensors are aligned by the center points of their corner pixels, preserving the values at the corner pixels. If set to ``False``, the input and output tensors are aligned by the corner points of their corner pixels, and the interpolation uses edge value padding for out-of-boundary values, making this operation *independent* of input size when :attr:`scale_factor` is kept the same. This only has an effect when :attr:`mode` is ``'linear'``, ``'bilinear'``, ``'bicubic'`` or ``'trilinear'``. Default: ``False`` .. note:: With ``mode='bicubic'``, it's possible to cause overshoot, in other words it can produce negative values or values greater than 255 for images. Explicitly call ``result.clamp(min=0, max=255)`` if you want to reduce the overshoot when displaying the image. .. warning:: With ``align_corners = True``, the linearly interpolating modes (`linear`, `bilinear`, and `trilinear`) don't proportionally align the output and input pixels, and thus the output values can depend on the input size. This was the default behavior for these modes up to version 0.3.1. Since then, the default behavior is ``align_corners = False``. See :class:`~torch.nn.Upsample` for concrete examples on how this affects the outputs. zLnn.functional.upsample is deprecated. Use nn.functional.interpolate instead.)rr interpolate)rr.rBrrCr6r6r7rD| s9 )rr.rBrrCrecompute_scale_factorr#cCsdS)Nr6)rr.rBrrCrFr6r6r7rE srEcCsdS)Nr6)rr.rBrrCrFr6r6r7rE scCsdS)Nr6)rr.rBrrCrFr6r6r7rE scCsdS)Nr6)rr.rBrrCrFr6r6r7rE s c str"ttf|||dS|d#kr<|dk rXtdn|dkrXtjdj|d}jd}dk r~dk r~td nֈdk rdkstdt t t frt |krtd j|t }nfd d t |D}nrdk rLdkstd}t t t fr4t |kr.td j|t nfdd t |Dntd|dkrdk rxDD]"}tj||krntjdPqnWn|rdk rtd|dkr|dkrd}|dk r4|r4tjj r tjjr fdd t |D}n&dk stfdd t |D}djdkr^|dkr^tjjj|Sjdkr|dkrtjjj|Sjdkr|dkrtjjj|Sjdkr|dkr|dk stt|Sjdkr|dkr|dk stt|SjdkrB|dkrB|dk s8tt|Sjdkr||dkr||dk shttjjj||Sjdkr|dkr|dk sttjjj||Sjdkr|dkr|dk sttjjj||Sjdkr*|dkr*|dk sttjjj||SjdkrJ|dkrJt djdkrj|dkrjt djdkr|dkrt djdkr|dkrt djdkr|dkrt d jdkr|dkrt d!t d"jj|dS)$aDown/up samples the input to either the given :attr:`size` or the given :attr:`scale_factor` The algorithm used for interpolation is determined by :attr:`mode`. Currently temporal, spatial and volumetric sampling are supported, i.e. expected inputs are 3-D, 4-D or 5-D in shape. The input dimensions are interpreted in the form: `mini-batch x channels x [optional depth] x [optional height] x width`. The modes available for resizing are: `nearest`, `linear` (3D-only), `bilinear`, `bicubic` (4D-only), `trilinear` (5D-only), `area` Args: input (Tensor): the input tensor size (int or Tuple[int] or Tuple[int, int] or Tuple[int, int, int]): output spatial size. scale_factor (float or Tuple[float]): multiplier for spatial size. If `scale_factor` is a tuple, its length has to match `input.dim()`. mode (str): algorithm used for upsampling: ``'nearest'`` | ``'linear'`` | ``'bilinear'`` | ``'bicubic'`` | ``'trilinear'`` | ``'area'``. Default: ``'nearest'`` align_corners (bool, optional): Geometrically, we consider the pixels of the input and output as squares rather than points. If set to ``True``, the input and output tensors are aligned by the center points of their corner pixels, preserving the values at the corner pixels. If set to ``False``, the input and output tensors are aligned by the corner points of their corner pixels, and the interpolation uses edge value padding for out-of-boundary values, making this operation *independent* of input size when :attr:`scale_factor` is kept the same. This only has an effect when :attr:`mode` is ``'linear'``, ``'bilinear'``, ``'bicubic'`` or ``'trilinear'``. Default: ``False`` recompute_scale_factor (bool, optional): recompute the scale_factor for use in the interpolation calculation. 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 `recomputed_scale_factor` is ``False``, then `size` or `scale_factor` will be used directly for interpolation. .. note:: With ``mode='bicubic'``, it's possible to cause overshoot, in other words it can produce negative values or values greater than 255 for images. Explicitly call ``result.clamp(min=0, max=255)`` if you want to reduce the overshoot when displaying the image. .. warning:: With ``align_corners = True``, the linearly interpolating modes (`linear`, `bilinear`, and `trilinear`) don't proportionally align the output and input pixels, and thus the output values can depend on the input size. This was the default behavior for these modes up to version 0.3.1. Since then, the default behavior is ``align_corners = False``. See :class:`~torch.nn.Upsample` for concrete examples on how this affects the outputs. .. warning:: When scale_factor is specified, if recompute_scale_factor=True, scale_factor is used to compute the output_size which will then be used to infer new scales for the interpolation. The default behavior for recompute_scale_factor changed to False in 1.6.0, and scale_factor is used in the interpolation calculation. Note: {backward_reproducibility_note} )r.rBrrCrFrAareaNzjalign_corners option can only be set with the interpolating modes: linear | bilinear | bicubic | trilinearzDefault upsampling behavior when mode={} is changed to align_corners=False since 0.4.0. Please specify align_corners=True if the old behavior is desired. See the documentation of nn.Upsample for details.Fr z2only one of size or scale_factor should be definedz;size shape must match input shape. Input is {}D, size is {}csg|]}qSr6r6).0r)r.r6r7 Iszinterpolate..zKscale_factor shape must match input shape. Input is {}D, scale_factor is {}csg|]}qSr6r6)rHr)rBr6r7rIUsz-either size or scale_factor should be definedaXThe default behavior for interpolate/upsample with float scale_factor changed in 1.6.0 to align with other frameworks/libraries, and now uses scale_factor directly, instead of relying on the computed output size. If you wish to restore the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. z?recompute_scale_factor is not meaningful with an explicit size.Tcs<g|]4}tjj|djtj|tjdjqS)r )r%)r0floorr.floatZtensorZfloat32)rHr)r scale_factorsr6r7rIuscs0g|](}ttjtj|d|qS)r )r-r"rJrKr.)rHr)rrLr6r7rIzsr$r9rrZ trilinearbicubicz.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 inputzInput Error: Only 3D, 4D and 5D input Tensors supported (got {}D) for the modes: nearest | linear | bilinear | bicubic | trilinear (got {}))rArG)!rrrEr+rrrVr/r,r]r^tuplerTrSr"rJr0rHrr2Z_get_tracing_stater3Zupsample_nearest1dZupsample_nearest2dZupsample_nearest3dadaptive_avg_pool1dryr{Zupsample_linear1dZupsample_bilinear2dZupsample_trilinear3dZupsample_bicubic2dr) rr.rBrrCrFr/rZscaler6)rrBrLr.r7rE sE              )rr.rBr#cCsdS)Nr6)rr.rBr6r6r7upsample_nearestsrQcCsdS)Nr6)rr.rBr6r6r7rQscCstjdt|||ddS)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} zTnn.functional.upsample_nearest is deprecated. Use nn.functional.interpolate instead.rA)r)rrrE)rr.rBr6r6r7rQs cCsdS)Nr6)rr.rBr6r6r7upsample_bilinearsrRcCsdS)Nr6)rr.rBr6r6r7rRscCsdS)Nr6)rr.rBr6r6r7rRscCsdS)Nr6)rr.rBr6r6r7rRscCstjdt|||dddS)ahUpsamples 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} zUnn.functional.upsample_bilinear is deprecated. Use nn.functional.interpolate instead.rT)rrC)rrrE)rr.rBr6r6r7rRs )rrArN)zerosborder reflectionrS)rgridr padding_moderCr#c Cst||r$tt||f|||||dS|dkrJ|dkrJ|dkrJtdj||dkrp|dkrp|dkrptd j||dkr~d }n|dkrd }nd }|dkrd }n|dkrd }nd }|d krtjdd}tj|||||S)aGiven 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 )rrWrCrrArNzbnn.functional.grid_sample(): expected mode to be 'bilinear', 'nearest' or 'bicubic', but got: '{}'rSrTrUzjnn.functional.grid_sample(): expected padding_mode to be 'zeros', 'border', or 'reflection', but got: '{}'rrr NzDefault 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) rr grid_sampler+rVrrr0Z grid_sampler)rrVrrWrCrZpadding_mode_enumr6r6r7rXs4j rX)thetar.rCr#cCsLt|rtt|f|||dS|dkr2tjdd}|jsJtdj|jt |dkr|j dks~|j ddks~|j ddkrtd j||j |dd}ndt |d kr|j dks|j ddks|j ddkrtd j||j |dd}nt d j||r"t |d kr"tjdnt |dkr>tdj|tj|||S)a} Generates a 2D or 3D flow field (sampling grid), given a batch of affine matrices :attr:`theta`. .. note:: This function is often used in conjunction with :func:`grid_sample` to build `Spatial Transformer Networks`_ . Args: theta (Tensor): input batch of affine matrices with shape (:math:`N \times 2 \times 3`) for 2D or (:math:`N \times 3 \times 4`) for 3D size (torch.Size): the target output image size. (:math:`N \times C \times H \times W` for 2D or :math:`N \times C \times D \times H \times W` for 3D) Example: torch.Size((32, 3, 24, 24)) align_corners (bool, optional): if ``True``, consider ``-1`` and ``1`` to refer to the centers of the corner pixels rather than the image corners. Refer to :func:`grid_sample` for a more complete description. A grid generated by :func:`affine_grid` should be passed to :func:`grid_sample` with the same setting for this option. Default: ``False`` Returns: output (Tensor): output Tensor of size (:math:`N \times H \times W \times 2`) .. _`Spatial Transformer Networks`: https://arxiv.org/abs/1506.02025 .. warning:: When ``align_corners = True``, the grid positions depend on the pixel size relative to the input image size, and so the locations sampled by :func:`grid_sample` will differ for the same input given at different resolutions (that is, after being upsampled or downsampled). The default behavior up to version 1.2.0 was ``align_corners = True``. Since then, the default behavior has been changed to ``align_corners = False``, in order to bring it in line with the default for :func:`interpolate`. .. warning:: When ``align_corners = True``, 2D affine transforms on 1D data and 3D affine transforms on 2D data (that is, when one of the spatial dimensions has unit size) are ill-defined, and not an intended use case. This is not a problem when ``align_corners = False``. Up to version 1.2.0, all grid points along a unit dimension were considered arbitrarily to be at ``-1``. From version 1.3.0, under ``align_corners = True`` all grid points along a unit dimension are considered to be at ``0`` (the center of the input image). )rCNzDefault 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.Fz6Expected theta to have floating point type, but got {}r9r$r rzJExpected a batch of 2D affine matrices of shape Nx2x3 for size {}. Got {}.rMzJExpected a batch of 3D affine matrices of shape Nx3x4 for size {}. Got {}.zfaffine_grid only supports 4D and 5D sizes, for 2D and 3D affine transforms, respectively. Got size {}.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.rz/Expected non-zero, positive output size. Got {}r'r(r'r'r(r))rr affine_gridrrrr+rVr%rTr/rrrr0Zaffine_grid_generator)rYr.rCZ spatial_sizer6r6r7rZs:0 ( ( rZconstant)rrrrr#cCst|rtt|f||||dSt|ddks6tdt|d|jksRtd|dkrhtj|||S|dks~tdj|t|dkr|jdks|jd kr|d krt j j j ||S|d krt j j j ||S|d krt||Stnt|d krd|jd ks|jd krd|d kr0t j j j||S|d krJt j j j||S|d kr^t||Stnt|dkr|jd ks|jdkr|d krt j j j||S|d krt j j j||S|d krt||StntddS)a` Pads tensor. Padding size: The padding size by which to pad some dimensions of :attr:`input` are described starting from the last dimension and moving forward. :math:`\left\lfloor\frac{\text{len(pad)}}{2}\right\rfloor` dimensions of ``input`` will be padded. For example, to pad only the last dimension of the input tensor, then :attr:`pad` has the form :math:`(\text{padding\_left}, \text{padding\_right})`; to pad the last 2 dimensions of the input tensor, then use :math:`(\text{padding\_left}, \text{padding\_right},` :math:`\text{padding\_top}, \text{padding\_bottom})`; to pad the last 3 dimensions, use :math:`(\text{padding\_left}, \text{padding\_right},` :math:`\text{padding\_top}, \text{padding\_bottom}` :math:`\text{padding\_front}, \text{padding\_back})`. Padding mode: See :class:`torch.nn.ConstantPad2d`, :class:`torch.nn.ReflectionPad2d`, and :class:`torch.nn.ReplicationPad2d` for concrete examples on how each of the padding modes works. Constant padding is implemented for arbitrary dimensions. Replicate and reflection padding is implemented for padding the last 3 dimensions of 5D input tensor, or the last 2 dimensions of 4D input tensor, or the last dimension of 3D input tensor. 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]) )rrr rz%Padding length must be divisible by 2zPadding length too larger[gz1Padding mode "{}"" doesn't take in value argumentr$ZreflectZ replicateZcircularr9rLrMzKOnly 2D, 3D, 4D, 5D padding with non-constant padding are supported for nowN)rr_padrTr,r/rZconstant_pad_ndrVr0r2r3Zreflection_pad1dZreplication_pad1d _pad_circularrZreflection_pad2dZreplication_pad2dZreflection_pad3dZreplication_pad3d)rrrrr6r6r7r\s@:$ *    *    r\)x1x2r}rrr#c Cs6t||r$tt||f|||||dStj|||||S)z< See :class:`torch.nn.PairwiseDistance` for details )r}rr)rrpairwise_distancer0)r^r_r}rrr6r6r7r`zs r`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 \cdot \Vert x_2 \Vert _2, \epsilon)} Supports :ref:`type promotion `. 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) aa one_hot(tensor, num_classes=-1) -> LongTensor Takes LongTensor with index values of shape ``(*)`` and returns a tensor of shape ``(*, num_classes)`` that have zeros everywhere except where the index of last dimension matches the corresponding value of the input tensor, in which case it will be 1. See also `One-hot on Wikipedia`_ . .. _One-hot on Wikipedia: https://en.wikipedia.org/wiki/One-hot Arguments: tensor (LongTensor): class values of any shape. num_classes (int): Total number of classes. If set to -1, the number of classes will be inferred as one greater than the largest class value in the input tensor. Returns: LongTensor that has one more dimension with 1 values at the index of last dimension indicated by the input, and 0 everywhere else. Examples: >>> F.one_hot(torch.arange(0, 5) % 3) tensor([[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 0, 0], [0, 1, 0]]) >>> F.one_hot(torch.arange(0, 5) % 3, num_classes=5) tensor([[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [1, 0, 0, 0, 0], [0, 1, 0, 0, 0]]) >>> F.one_hot(torch.arange(0, 6).view(3,2) % 3) tensor([[[1, 0, 0], [0, 1, 0]], [[0, 0, 1], [1, 0, 0]], [[0, 1, 0], [0, 0, 1]]]) ) anchorpositivenegativer8r}rswaprrr r#c Csrt|||r2tt|||f|||||||||| d S|dk sB|dk rPtj||} n tj| } tj|||||||| S)z> See :class:`~torch.nn.TripletMarginLoss` for details )r8r}rrdrrr N)rrtriplet_margin_lossrr'rr0) rarbrcr8r}rrdrrr r(r6r6r7res$  re)distance_functionr8rdr )rarbrcrfr8rdr r#c Cstjjrtdt|||r>tt|||f|||||||d S|dk rJ|nt}|||}|||}|r||||} tj|| }tj |||dd} t j |} | dkr| j S| dkr| j S| SdS)zK See :class:`~torch.nn.TripletMarginWithDistanceLoss` for details. zuF.triplet_margin_with_distance_loss does not support JIT scripting: functions requiring Callables cannot be scripted.)rfr8rdr Ng)rrr )r0rHrrrr!triplet_margin_with_distance_lossr`rclamprrrr) rarbrcrfr8rdr Z positive_distZ negative_distZ swap_distoutputr(r6r6r7rgs6       rg-q=)rr}r/rrmr#c Cst||r$tt||f|||||dS|dkrP|j||ddj|j|}||S|j||ddj|j|}tj|||dSdS)aLPerforms :math:`L_p` normalization of inputs over specified dimension. For a tensor :attr:`input` of sizes :math:`(n_0, ..., n_{dim}, ..., n_k)`, each :math:`n_{dim}` -element vector :math:`v` along dimension :attr:`dim` is transformed as .. math:: v = \frac{v}{\max(\lVert v \rVert_p, \epsilon)}. With the default arguments it uses the Euclidean norm over vectors along dimension :math:`1` for normalization. Args: input: input tensor of any shape p (float): the exponent value in the norm formulation. Default: 2 dim (int): the dimension to reduce. Default: 1 eps (float): small value to avoid division by zero. Default: 1e-12 out (Tensor, optional): the output tensor. If :attr:`out` is used, this operation won't be differentiable. )r}r/rrmNT)r)rm) rr normalizeZnormZ clamp_minZ expand_asZ clamp_min_r0r)rr}r/rrmZdenomr6r6r7rkIs rk)argr:messager#cCs(t|ts$t|dks$t|j|dS)Nr )r]r-rTr,rV)rlr:rmr6r6r7assert_int_or_pairfsrn)rrrErDrCr#c Cst|r tt|f|||||dS|jdkrd}t|d|t|d|t|d|t|d|tjjj|t |t |t |t |St dj |jd S) a Extracts 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 )rErDrCr9z&{} must be int or 2-tuple for 4D inputrrErDrCz:Input Error: Only 4D input Tensors are supported (got {}D)N) rrunfoldr/rnr0r2r3Zim2colrrrV)rrrErDrCmsgr6r6r7rojs     &ro)rrrrErDrCr#c Cst|r"tt|f||||||dS|jdkrd}t|d|t|d|t|d|t|d|t|d|tjjj|t |t |t |t |t |St d j |jd S) zCombines an array of sliding local blocks into a large containing tensor. .. warning:: Currently, only 3-D output tensors (unfolded batched image-like tensors) are supported. See :class:`torch.nn.Fold` for details )rErDrCr$z&{} must be int or 2-tuple for 3D inputrrrErDrCz:Input Error: Only 3D input Tensors are supported (got {}D)N) rrfoldr/rnr0r2r3Zcol2imrrrV)rrrrErDrCrpr6r6r7rqs      $rq)rrDr#cCs|j}|dd}t|}xt|D]x\}}||dd |ksJtd||dd |kshtd||dd ||dd |dks$tdq$W|dd}xBt|D]6\}}||||dd ||dd f7}qWtj||j|j|jd}|dkr~t |d d} |dt |dd} t |d d} |dt |d d} |d| | f|d| | f<n|dkrLt |dd} |dt |dd} t |dd} |d t |dd}t |d d} |dt |d d} t |d d}|d t |d d}|d| | ||f|d| | | |f<n"|d krnt |dd} |dt |dd} t |dd} |d t |dd}t |dd}|d t |dd}t |d d} |dt |d  d} t |d! d}|d t |d" d}t |d# d}|d t |d$ d}|d| | ||||f|d| | | |||f<|d%dkr|d|d&t |d'd}|dt |d(d}d}|d)}|dddd||f|dddd||f<|d*dkrft |d+d}t |d,d|d-}|d|d.}|d}|dddd||f|dddd||f<t|dkr|d/dkr|d |d0t |d1d}|d t |d2d}d}|d3}|dddddd||f|dddddd||f<|d4dkrt |d5d}t |d6d|d7}|d |d8}|d }|dddddd||f|dddddd||f<t|d kr|d9dkr(|d |d:t |d;d}|d t |d<d}d}|d=}|dddddddd||f|dddddddd||f<|d>dkrt |d?d}t |d@d|dA}|d |dB}|d }|dddddddd||f|dddddddd||f<|S)CaCircularly pads tensor. Tensor values at the beginning are used to pad the end, and values at the end are used to pad the beginning. For example, consider a single dimension with values [0, 1, 2, 3]. With circular padding of (1, 1) it would be padded to [3, 0, 1, 2, 3, 0], and with padding (1, 2) it would be padded to [3, 0, 1, 2, 3, 0, 1]. If negative padding is applied then the ends of the tensor get removed. With circular padding of (-1, -1) the previous example would become [1, 2]. Circular padding of (-1, 1) would produce [1, 2, 3, 1]. The first and second dimensions of the tensor are not padded. Args: input: Tensor with shape :math:`(N, C, D[, H, W])`. padding: Tuple containing the number of elements to pad each side of the tensor. The length of padding must be twice the number of paddable dimensions. For example, the length of padding should be 4 for a tensor of shape :math:`(N, C, H, W)`, and the length should be 6 for a tensor of shape :math:`(N, C, D, H, W)`. Examples:: >>> x = torch.tensor([[[[0, 1, 2], [3, 4, 5]]]]) # Create tensor >>> # Example 1 >>> padding = (1, 1, 1, 1) >>> y = F.pad(x, padding, mode='circular') >>> print(y) tensor([[[[5, 3, 4, 5, 3], [2, 0, 1, 2, 0], [5, 3, 4, 5, 3], [2, 0, 1, 2, 0]]]]) >>> print(y.shape) torch.Size([1, 1, 4, 5]) >>> # Example 2 >>> padding = (1, 1, 2, 2) >>> z = F.pad(x, padding, mode='circular') >>> print(z) tensor([[[[2, 0, 1, 2, 0], [5, 3, 4, 5, 3], [2, 0, 1, 2, 0], [5, 3, 4, 5, 3], [2, 0, 1, 2, 0], [5, 3, 4, 5, 3]]]]) >>> print(z.shape) torch.Size([1, 1, 6, 5]) r Nrz4Padding value causes wrapping around more than once.rz:Negative padding value is resulting in an empty dimension.)r%layoutr&.r9r$rLrMr'r(r'r(r'r(r)r'r(rsr)r'r(rsr)ir'r(rsr)irtr'r'r(r(r'r(r'r'r(r(rsrsr)r)rsr)rsrsr)r)iirtrtirtiirtrt) rrT enumerater,r0emptyr%rrr&r)rrDZin_shapeZpaddable_shaperidxr.Z out_shapermZout_d0Zout_d1Zin_d0Zin_d1Zout_h0Zout_h1Zin_h0Zin_h1Zout_w0Zout_w1Zin_w0Zin_w1Zi0i1Zo0Zo1r6r6r7r]s0 .  2   , 4 00<<HHr])qrvwbr#cCs|jd}||kr||kr0t|||jdddS|j||dg\}}|dkrXd}} n|j||dg\}} t|||ft||| jdddSnX|jd\}} } |dkrd}} } n|jd\}} } t|||t|| | t|| | fSdS) aK Performs 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. rr$)r/r Nr(r(r()r.rchunksplit)ryrrzr{r|Ew_qZw_kvb_qZb_kvw_kw_vb_kb_vr6r6r7_in_projection_packed\s"  &r) ryrrzrrrrrrr#c CsD|jd |jd |jd } } } |j| | fksJtd| | fd|j|j| | fksrtd| | fd|j|j| | fkstd| | fd|j|dks|j| fkstd| fd|j|dks|j| fkstd| fd|j|dks"|j| fks"td | fd|jt|||t|||t|||fS) a Performs 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]` rz!expecting query weights shape of z , but got zexpecting key weights shape of z!expecting value weights shape of Nzexpecting query bias shape of zexpecting key bias shape of zexpecting value bias shape of r(r(r()r.rr,r) ryrrzrrrrrrEqZEkZEvr6r6r7_in_projections+"(((,,0r)ryrrz attn_mask dropout_pr#c Csr|j\}}}|tj|}tj||jdd}|dk r>||7}t|d d}|dkr^t||d}tj||} | |fS) a 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. Returns a tensor pair containing attended values and attention weights. Args: q, k, v: query, key and value tensors. See Shape section for shape details. attn_mask: optional tensor containing mask values to be added to calculated attention. May be 2D or 3D; see Shape section for details. dropout_p: dropout probability. If greater than 0.0, dropout is applied. Shape: - q: :math:`(B, Nt, E)` where B is batch size, Nt is the target sequence length, and E is embedding dimension. - key: :math:`(B, Ns, E)` where B is batch size, Ns is the source sequence length, and E is embedding dimension. - value: :math:`(B, Ns, E)` where B is batch size, Ns is the source sequence length, and E is embedding dimension. - attn_mask: either a 3D tensor of shape :math:`(B, Nt, Ns)` or a 2D tensor of shape :math:`(Nt, Ns)`. - Output: attention values have shape :math:`(B, Nt, E)`; attention weights have shape :math:`(B, Nt, Ns)` r rN)r/g)r}r'r(r()rr"sqrtr0Zbmm transposerr) ryrrzrrBZNtrZattnrir6r6r7_scaled_dot_product_attentions    r)querykeyrembed_dim_to_check num_headsin_proj_weight in_proj_biasbias_kbias_v add_zero_attnrout_proj_weight out_proj_biasr~key_padding_mask need_weightsruse_separate_proj_weight q_proj_weight k_proj_weight v_proj_weightstatic_kstatic_vr#c*Cs|||||||| | f }t|rXtt||||||||||| | | | | |||||||||dS|j\}}}|j\}}}||kstd|d|t|tjr|j|dd}n||}|||kstd|d||r|jdd |jdd ksDtd |jdd d |jdd n&|j|jksDtd |jd |j|sbt |||||\}}} n||dk sttd|dk std|dk std|dkrd}!}"}#n|j d\}!}"}#t |||||||!|"|# \}}} |dk r|j tj krtjd|jtj}n(|js6|j tjks6td|j |jd kr|||f}$|j|$krptd|jd|$d|jd}nV|jdkr||||f}%|j|%krtd|jd|%dntd|jd|dk r|j tj krtjd|jtj}|dk r|dk r|dks&td|dks8tdtj||jd|dg}tj| |jd|dg} |dk r|t|d)}|dk rt|d*}n|dkst|dkst|jj||||jdd}|dkr|jj|jd|||jdd}n`|jd||ks.td||d|jd|jd |ksXtd |d|jd |}|dkr| jj| jd|||jdd} n`|jd||kstd!||d|jd|jd |kstd"|d|jd |} | rl||d|f}&tj|tj|&|j |jd#gdd$}tj| tj|&| j | jd#gdd$} |dk rXt|d+}|dk rlt|d,}|jd}|dk r|j||fkstd%||fd|j|j|dd|jd-|d.d/j ||d|}|dkr|}n*|j tjkr|j!|}n|j"|t#d&}|dk rJ|j tjkrJtj$|tj#d'}'|'j%|t#d&|'}| sTd(} t&||| || \}(})|(jddjj|||}(t'|(| | }(|r|)j||||})|(|)j(dd$|fS|(dfSdS)0a? Args: query, key, value: map a query and a set of key-value pairs to an output. See "Attention Is All You Need" for more details. embed_dim_to_check: total dimension of the model. num_heads: parallel attention heads. in_proj_weight, in_proj_bias: input projection weight and bias. bias_k, bias_v: bias of the key and value sequences to be added at dim=0. add_zero_attn: add a new batch of zeros to the key and value sequences at dim=1. dropout_p: probability of an element to be zeroed. out_proj_weight, out_proj_bias: the output projection weight and bias. training: apply dropout if is ``True``. key_padding_mask: if provided, specified padding elements in the key will be ignored by the attention. This is an binary mask. When the value is True, the corresponding value on the attention layer will be filled with -inf. need_weights: output attn_output_weights. attn_mask: 2D or 3D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all the batches while a 3D mask allows to specify a different mask for the entries of each batch. use_separate_proj_weight: the function accept the proj. weights for query, key, and value in different forms. If false, in_proj_weight will be used, which is a combination of q_proj_weight, k_proj_weight, v_proj_weight. q_proj_weight, k_proj_weight, v_proj_weight, in_proj_bias: input projection weight and bias. static_k, static_v: static key and value used for attention operators. Shape: Inputs: - query: :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is the embedding dimension. - key: :math:`(S, N, E)`, where S is the source sequence length, N is the batch size, E is the embedding dimension. - value: :math:`(S, N, E)` where S is the source sequence length, N is the batch size, E is the embedding dimension. - key_padding_mask: :math:`(N, S)` where N is the batch size, S is the source sequence length. If a ByteTensor is provided, the non-zero positions will be ignored while the zero positions will be unchanged. If a BoolTensor is provided, the positions with the value of ``True`` will be ignored while the position with the value of ``False`` will be unchanged. - attn_mask: 2D mask :math:`(L, S)` where L is the target sequence length, S is the source sequence length. 3D mask :math:`(N*num_heads, L, S)` where N is the batch size, L is the target sequence length, S is the source sequence length. attn_mask ensures that position i is allowed to attend the unmasked positions. If a ByteTensor is provided, the non-zero positions are not allowed to attend while the zero positions will be unchanged. If a BoolTensor is provided, positions with ``True`` are not allowed to attend while ``False`` values will be unchanged. If a FloatTensor is provided, it will be added to the attention weight. - static_k: :math:`(N*num_heads, S, E/num_heads)`, where S is the source sequence length, N is the batch size, E is the embedding dimension. E/num_heads is the head dimension. - static_v: :math:`(N*num_heads, S, E/num_heads)`, where S is the source sequence length, N is the batch size, E is the embedding dimension. E/num_heads is the head dimension. Outputs: - attn_output: :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is the embedding dimension. - attn_output_weights: :math:`(N, L, S)` where N is the batch size, L is the target sequence length, S is the source sequence length. ) r~rrrrrrrrrz%was expecting embedding dimension of z , but got trunc)Z rounding_modez embed_dim z not divisible by num_heads Nr zkey'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 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$zZByte tensor for attn_mask in nn.MultiheadAttention is deprecated. Use bool tensor instead.zBOnly float, byte, and bool types are supported for attn_mask, not z!The shape of the 2D attn_mask is z, but should be .rz!The shape of the 3D attn_mask is zattn_mask's dimension z is not supportedzaByte tensor for key_padding_mask in nn.MultiheadAttention is deprecated. Use bool tensor instead.z#bias cannot be added to static key.z%bias cannot be added to static value.rzexpecting static_k.size(0) of zexpecting static_k.size(2) of zexpecting static_v.size(0) of zexpecting static_v.size(2) of )r%r&)r/z$expecting key_padding_mask shape of z-inf)r%g)rr)rr)rr)rrr(r(r())rrmulti_head_attention_forwardrr,r]r0Tensorrrr}rr%Zuint8rrZtoboolrr/rr`catrepeatrrrrr.rSr&r-r logical_orZ masked_fillrKrZ masked_fill_rrr)*rrrrrrrrrrrrrr~rrrrrrrrrZtens_opsZtgt_lenZbszZ embed_dimZsrc_lenrZhead_dimryrrzrrrZcorrect_2d_sizeZcorrect_3d_sizeZzero_attn_shapeZ new_attn_maskZ attn_outputZattn_output_weightsr6r6r7rsQ      (&             & &""         r)NNFN)NNFN)NNFN)NNFN)NrrFF)NrrFF)NrrFF)NrrFF)NrrFF)NrrFF)NrN)NrN)NrN)NF)NF)F)F)F)F)F)F)r|TF)r|FF)r|TF)r|TF)r|FF)F)Fr()r()rrF)F)rF)F)rF)rF?UUUUUU?)rrFF)r|)Nr$N)Nr$Nr()rFrr()Nr$N)F)N)N)F)F)F)NNrFF) NNr FrFNFN)NNFrr)NNNNTrr)NNr)NNr)rrr)rrF)NNrNr)TFNrNr)Frr)NNrF)NNrNrr))NNNr)NNNrN)NNrr)rr)NNr)NNr)rNNr)rNNr)NNr)NNr)NNNr)rNNr)rrNNNr)NNrAN)NNrAN)NNrAN)NNrANN)NNrANN)NNrANN)NNrANN)NNrANN)NN)NN)NN)NN)NN)NN)NN)NN)rrSN)N)r[r))rrF)rr rFNNr)rrrjN)rrr)rrr)N)NNN)Nr)) TNTNFNNNNN)__doc__typingrrrrr"rr0rZtorch._CrrZtorch._torch_docsr r Z _jit_internalr r rrrZ overridesrrrrrrrmodulesrZ modules.utilsrrrrrZconv1drVZconv2dZconv3dZconv_transpose1dZconv_transpose2dZconv_transpose3dZconv_tbcror2r3rfrr-rKrr*r8__name__r4r@rBrArGrKrJrMrOrNrPrRrQrZr\r_rcrernrprrrqrsrurtrvrxrwrPryr{rrrrrrrrrirrrrrrrrrrrrrrrrZ log_sigmoidr>rrrrZsoftplusrrrrrrZ softshrinkrrrrrrrrrrrrrrrrrrr rrrr&r+r,r/r0r5r6r7r9r:r;r<r=r?r@Z pixel_shuffleZpixel_unshuffleZchannel_shufflerDrErQrRZGRID_SAMPLE_INTERPOLATION_MODESZGRID_SAMPLE_PADDING_MODESrXrZr\rr`ZpdistZcosine_similarityZone_hotrergrkrnrorqr]rrrrr6r6r6r7s0            (8((<(&&&&&&"(!((       ""$>"  \*-$ $  +8><QN LA">" "*  &04=:>6$8Z(,  &a$f" - &+&$$/9"/6^