a
    àñh�÷  ã                   @   sÈ  d dl mZmZmZmZmZmZ d dlZd dlm	  m
Z d dlmZ ddlmZmZ ddlmZmZ ddlmZmZ ddlmZ ejZd d	lmZ g d
¢Zdd„ Zdgdd„Zer¸eZnee Zeeee  dœdd„Z dd„ Z!dhdd„Z"dd„ Z#e�reeee f eedf dœdd„Z$ndd„ Z$dd„ Z%dieeee ee ee e&e'e&ee& ee& ed"œd#d$„Z(djeeee ee ee e&e&ee& ee e&ed%œd&d'„Z)e`*e�r®eZ+neeeef Z+dkee&e&e&ee e+d(œd)d*„Z,dlee&e&ee e+d+œd,d-„Z-dmd.d/„Z.dnd0d1„Z/dod2d3„Z0ed4d5d!e.e/e1d6d7�Z2ed4d5d!e,e0e1d6d7�Z3ed8d9d!e3e2e1d6d7�Z4e,j5e4_5dpd:d;„Z6dqd<d=„Z7drd>d?„Z8ed4dd!e6e7e1d@d7�Z9ed4dd!e-e8e1d@d7�Z:ed8d9d!e:e9e1d@d7�Z;e-j5e;_5dsdAdB„Z<dCdD„ Z=dEdF„ Z>dtdIdJ„Z?dKdL„ Z@dMdN„ ZAdOdP„ ZBe�r
n8edudRdS„ƒZCedvdTdS„ƒZCedwdUdS„ƒZCedxdVdS„ƒZCdydWdS„ZCdXdY„ ZDdzdZd[„ZEe�rnee ZFnee ZFee&eFdd\œd]d^„ZGd{d_d`„ZHd|dadb„ZIedcd9d!eHeIe1ddd7�ZJeEj5eJ_5dedf„ ZKdS )}é    )ÚTupleÚOptionalÚUnionÚAnyÚSequenceÚTYPE_CHECKINGN)Ú_sizeé   )Úsvd_lowrankÚpca_lowrank)Úhas_torch_functionÚhandle_torch_function)Úboolean_dispatchÚList)Ú	_overload)Ú_VF)Ú
atleast_1dÚ
atleast_2dÚ
atleast_3dÚalign_tensorsÚbroadcast_tensorsÚcartesian_prodÚ
block_diagÚcdistÚchain_matmulÚeinsumÚistftÚluÚ	lu_unpackÚnormÚmeshgridr   ÚsplitÚstftr
   Ú	tensordotÚuniqueÚunique_consecutivec                  G   s@   t j ¡ s6tdd„ | D ƒƒr6t| ƒr6tt| g| ¢R Ž S t | ¡S )a   broadcast_tensors(*tensors) -> List of Tensors

    Broadcasts the given tensors according to :ref:`broadcasting-semantics`.

    Args:
        *tensors: any number of tensors of the same type

    .. warning::

        More than one element of a broadcasted 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 tensors, please clone them first.

    Example::

        >>> x = torch.arange(3).view(1, 3)
        >>> y = torch.arange(2).view(2, 1)
        >>> a, b = torch.broadcast_tensors(x, y)
        >>> a.size()
        torch.Size([2, 3])
        >>> a
        tensor([[0, 1, 2],
                [0, 1, 2]])
    c                 s   s   | ]}t |ƒtuV  qd S ©N©ÚtypeÚTensor©Ú.0Út© r-   úP/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torch/functional.pyÚ	<genexpr>E   ó    z$broadcast_tensors.<locals>.<genexpr>)ÚtorchÚjitÚis_scriptingÚanyr   r   r   r   ©Útensorsr-   r-   r.   r   *   s    
r   c                 C   s@   t j ¡ s4t| ƒtur4t| fƒr4tt| f| ||d�S |  ||¡S )a%  Splits the tensor into chunks. Each chunk is a view of the original tensor.

    If :attr:`split_size_or_sections` is an integer type, then :attr:`tensor` will
    be split into equally sized chunks (if possible). Last chunk will be smaller if
    the tensor size along the given dimension :attr:`dim` is not divisible by
    :attr:`split_size`.

    If :attr:`split_size_or_sections` is a list, then :attr:`tensor` will be split
    into ``len(split_size_or_sections)`` chunks with sizes in :attr:`dim` according
    to :attr:`split_size_or_sections`.

    Arguments:
        tensor (Tensor): tensor to split.
        split_size_or_sections (int) or (list(int)): size of a single chunk or
            list of sizes for each chunk
        dim (int): dimension along which to split the tensor.

    Example::
        >>> a = torch.arange(10).reshape(5,2)
        >>> a
        tensor([[0, 1],
                [2, 3],
                [4, 5],
                [6, 7],
                [8, 9]])
        >>> torch.split(a, 2)
        (tensor([[0, 1],
                 [2, 3]]),
         tensor([[4, 5],
                 [6, 7]]),
         tensor([[8, 9]]))
        >>> torch.split(a, [1,4])
        (tensor([[0, 1]]),
         tensor([[2, 3],
                 [4, 5],
                 [6, 7],
                 [8, 9]]))
    )Údim)r1   r2   r3   r(   r)   r   r   r!   )ÚtensorZsplit_size_or_sectionsr7   r-   r-   r.   r!   J   s    '
ÿr!   )ÚindicesÚreturnc                 C   sh   t j tt g ¡}|g}| D ]F}t j ttt  g ¡}|D ]"}t|ƒD ]}| ||g ¡ qFq:|}q|S r&   )r1   r2   Zannotater   ÚintÚrangeÚappend)r9   Z
empty_listÚresultÚidxZresult_tempÚresÚir-   r-   r.   Ú_indices_productƒ   s    rB   c                 C   s   | }|D ]}|| }q|S r&   r-   )r8   r9   ÚoutÚindexr-   r-   r.   Ú_index_tensor_with_indices_list�   s    
rE   Tc              
   C   s:  t j ¡ s@| |f}tdd„ |D ƒƒr@t|ƒr@tt|| |||d�S | j}|dd… \}}t||ƒ}|rÎ|  	¡ }	|	dusxJ ‚||krŽ|	 
dd|¡}	|  ¡ }
|
dus¢J ‚||kr¸|
 
dd|¡}
|
jddd� d	¡ nd }
}	|�r,|d	 }|  ¡ d
k�r¾t j|| j| jd� |dd… |f ¡jt jd�}|du�s2J ‚t|dd… ƒ}|D ]t}dd„ t|ƒD ƒ}tt||ƒƒD ]$\}}|| ||  ||< ||< �qjt||ƒ}| | d	t j||jd�¡¡ �qFnlt j|| j| jd�}dd„ t|ƒD ƒ}t|ƒD ]$\}}|| ||  ||< ||< �qì| d	t j||jd�¡}nd}||
|	fS )aC  Unpacks the data and pivots from a LU factorization of a tensor.

    Returns a tuple of tensors as ``(the pivots, the L tensor, the U tensor)``.

    Arguments:
        LU_data (Tensor): the packed LU factorization data
        LU_pivots (Tensor): the packed LU factorization pivots
        unpack_data (bool): flag indicating if the data should be unpacked
        unpack_pivots (bool): flag indicating if the pivots should be unpacked

    Examples::

        >>> A = torch.randn(2, 3, 3)
        >>> A_LU, pivots = A.lu()
        >>> P, A_L, A_U = torch.lu_unpack(A_LU, pivots)
        >>>
        >>> # can recover A from factorization
        >>> A_ = torch.bmm(P, torch.bmm(A_L, A_U))

        >>> # LU factorization of a rectangular matrix:
        >>> A = torch.randn(2, 3, 2)
        >>> A_LU, pivots = A.lu()
        >>> P, A_L, A_U = torch.lu_unpack(A_LU, pivots)
        >>> P
        tensor([[[1., 0., 0.],
                 [0., 1., 0.],
                 [0., 0., 1.]],

                [[0., 0., 1.],
                 [0., 1., 0.],
                 [1., 0., 0.]]])
        >>> A_L
        tensor([[[ 1.0000,  0.0000],
                 [ 0.4763,  1.0000],
                 [ 0.3683,  0.1135]],

                [[ 1.0000,  0.0000],
                 [ 0.2957,  1.0000],
                 [-0.9668, -0.3335]]])
        >>> A_U
        tensor([[[ 2.1962,  1.0881],
                 [ 0.0000, -0.8681]],

                [[-1.0947,  0.3736],
                 [ 0.0000,  0.5718]]])
        >>> A_ = torch.bmm(P, torch.bmm(A_L, A_U))
        >>> torch.norm(A_ - A)
        tensor(2.9802e-08)
    c                 S   s   g | ]}t |ƒtu‘qS r-   r'   r*   r-   r-   r.   Ú
<listcomp>Ì   r0   zlu_unpack.<locals>.<listcomp>)Úunpack_dataÚunpack_pivotséþÿÿÿNr   éÿÿÿÿ)Zdim1Zdim2r	   é   )ÚdeviceÚdtype)Zmemory_formatc                 S   s   g | ]}|‘qS r-   r-   ©r+   rA   r-   r-   r.   rF   ó   r0   )rL   c                 S   s   g | ]}|‘qS r-   r-   rN   r-   r-   r.   rF   û   r0   )r1   r2   r3   r4   r   r   r   ÚshapeÚminZtriuZnarrowZtrilZdiagonalZfill_r7   ZeyerL   rM   ÚexpandÚcloneZcontiguous_formatrB   r<   Ú	enumeraterE   Úcopy_Zindex_selectZ	as_tensor)ZLU_dataZ	LU_pivotsrG   rH   Ztens_opsrO   ÚmÚnÚkÚUÚLZLU_pivots_zero_idxÚPr9   r?   Zfinal_orderÚjZp_idxr-   r-   r.   r   —   s\    3

þ

ÿþý
$r   c                 G   sz   t j ¡ s8tdd„ |D ƒƒr8t|ƒr8tt|| g|¢R Ž S t|ƒdkrnt|d t	t
fƒrn|d }t| g|¢R Ž S t | |¡S )añ  einsum(equation, *operands) -> Tensor

This function provides a way of computing multilinear expressions (i.e. sums of products) using the
Einstein summation convention.

Args:
    equation (string): The equation is given in terms of lower case letters (indices) to be associated
           with each dimension of the operands and result. The left hand side lists the operands
           dimensions, separated by commas. There should be one index letter per tensor dimension.
           The right hand side follows after `->` and gives the indices for the output.
           If the `->` and right hand side are omitted, it implicitly defined as the alphabetically
           sorted list of all indices appearing exactly once in the left hand side.
           The indices not apprearing in the output are summed over after multiplying the operands
           entries.
           If an index appears several times for the same operand, a diagonal is taken.
           Ellipses `...` represent a fixed number of dimensions. If the right hand side is inferred,
           the ellipsis dimensions are at the beginning of the output.
    operands (Tensor): The operands to compute the Einstein sum of.

.. note::

    This function does not optimize the given expression, so a different formula for the same computation may
    run faster or consume less memory. Projects like opt_einsum (https://optimized-einsum.readthedocs.io/en/stable/)
    can optimize the formula for you.

Examples::

    >>> x = torch.randn(5)
    >>> y = torch.randn(4)
    >>> torch.einsum('i,j->ij', x, y)  # outer product
    tensor([[-0.0570, -0.0286, -0.0231,  0.0197],
            [ 1.2616,  0.6335,  0.5113, -0.4351],
            [ 1.4452,  0.7257,  0.5857, -0.4984],
            [-0.4647, -0.2333, -0.1883,  0.1603],
            [-1.1130, -0.5588, -0.4510,  0.3838]])


    >>> A = torch.randn(3,5,4)
    >>> l = torch.randn(2,5)
    >>> r = torch.randn(2,4)
    >>> torch.einsum('bn,anm,bm->ba', l, A, r) # compare torch.nn.functional.bilinear
    tensor([[-0.3430, -5.2405,  0.4494],
            [ 0.3311,  5.5201, -3.0356]])


    >>> As = torch.randn(3,2,5)
    >>> Bs = torch.randn(3,5,4)
    >>> torch.einsum('bij,bjk->bik', As, Bs) # batch matrix multiplication
    tensor([[[-1.0564, -1.5904,  3.2023,  3.1271],
             [-1.6706, -0.8097, -0.8025, -2.1183]],

            [[ 4.2239,  0.3107, -0.5756, -0.2354],
             [-1.4558, -0.3460,  1.5087, -0.8530]],

            [[ 2.8153,  1.8787, -4.3839, -1.2112],
             [ 0.3728, -2.1131,  0.0921,  0.8305]]])

    >>> A = torch.randn(3, 3)
    >>> torch.einsum('ii->i', A) # diagonal
    tensor([-0.7825,  0.8291, -0.1936])

    >>> A = torch.randn(4, 3, 3)
    >>> torch.einsum('...ii->...i', A) # batch diagonal
    tensor([[-1.0864,  0.7292,  0.0569],
            [-0.9725, -1.0270,  0.6493],
            [ 0.5832, -1.1716, -1.5084],
            [ 0.4041, -1.1690,  0.8570]])

    >>> A = torch.randn(2, 3, 4, 5)
    >>> torch.einsum('...ij->...ji', A).shape # batch permute
    torch.Size([2, 3, 5, 4])
c                 s   s   | ]}t |ƒtuV  qd S r&   r'   r*   r-   r-   r.   r/   O  r0   zeinsum.<locals>.<genexpr>r	   r   )r1   r2   r3   r4   r   r   r   ÚlenÚ
isinstanceÚlistÚtupler   )ZequationZoperandsZ	_operandsr-   r-   r.   r     s    I
r   .)r6   r:   c                  G   s   t | Ž S r&   ©Ú	_meshgridr5   r-   r-   r.   r    ]  s    r    c                  G   s   t | Ž S r&   r`   r5   r-   r-   r.   r    `  s    c                  G   sf   t j ¡ s6tdd„ | D ƒƒr6t| ƒr6tt| g| ¢R Ž S t| ƒdkr\t| d t	t
fƒr\| d } t | ¡S )a  Take :math:`N` tensors, each of which can be either scalar or 1-dimensional
vector, and create :math:`N` N-dimensional grids, where the :math:`i` :sup:`th` grid is defined by
expanding the :math:`i` :sup:`th` input over dimensions defined by other inputs.


    Args:
        tensors (list of Tensor): list of scalars or 1 dimensional tensors. Scalars will be
        treated as tensors of size :math:`(1,)` automatically

    Returns:
        seq (sequence of Tensors): If the input has :math:`k` tensors of size
        :math:`(N_1,), (N_2,), \ldots , (N_k,)`, then the output would also have :math:`k` tensors,
        where all tensors are of size :math:`(N_1, N_2, \ldots , N_k)`.

    Example::

        >>> x = torch.tensor([1, 2, 3])
        >>> y = torch.tensor([4, 5, 6])
        >>> grid_x, grid_y = torch.meshgrid(x, y)
        >>> grid_x
        tensor([[1, 1, 1],
                [2, 2, 2],
                [3, 3, 3]])
        >>> grid_y
        tensor([[4, 5, 6],
                [4, 5, 6],
                [4, 5, 6]])
    c                 s   s   | ]}t |ƒtuV  qd S r&   r'   r*   r-   r-   r.   r/   ‚  r0   z_meshgrid.<locals>.<genexpr>r	   r   )r1   r2   r3   r4   r   r   r    r\   r]   r^   r_   r   r5   r-   r-   r.   ra   d  s    
ra   ÚreflectF)ÚinputÚn_fftÚ
hop_lengthÚ
win_lengthÚwindowÚcenterÚpad_modeÚ
normalizedÚonesidedÚreturn_complexr:   c
                 C   sº   t j ¡ sBt| ƒturBt| fƒrBtt| f| |||||||||	d�S |r¢|  ¡ }
dgd|
  t	|  
¡ ƒ }t|d ƒ}t |  |¡||f|¡} |  | j|
 d… ¡} t | |||||||	¡S )aº  Short-time Fourier transform (STFT).

    .. warning::
        Setting :attr:`return_complex` explicitly will be required in a future
        PyTorch release. Set it to False to preserve the current behavior or
        True to return a complex output.

    The STFT computes the Fourier transform of short overlapping windows of the
    input. This giving frequency components of the signal as they change over
    time. The interface of this function is modeled after the librosa_ stft function.

    .. _librosa: https://librosa.org/doc/latest/generated/librosa.stft.html

    Ignoring the optional batch dimension, this method computes the following
    expression:

    .. math::
        X[m, \omega] = \sum_{k = 0}^{\text{win\_length-1}}%
                            \text{window}[k]\ \text{input}[m \times \text{hop\_length} + k]\ %
                            \exp\left(- j \frac{2 \pi \cdot \omega k}{\text{win\_length}}\right),

    where :math:`m` is the index of the sliding window, and :math:`\omega` is
    the frequency that :math:`0 \leq \omega < \text{n\_fft}`. When
    :attr:`onesided` is the default value ``True``,

    * :attr:`input` must be either a 1-D time sequence or a 2-D batch of time
      sequences.

    * If :attr:`hop_length` is ``None`` (default), it is treated as equal to
      ``floor(n_fft / 4)``.

    * If :attr:`win_length` is ``None`` (default), it is treated as equal to
      :attr:`n_fft`.

    * :attr:`window` can be a 1-D tensor of size :attr:`win_length`, e.g., from
      :meth:`torch.hann_window`. If :attr:`window` is ``None`` (default), it is
      treated as if having :math:`1` everywhere in the window. If
      :math:`\text{win\_length} < \text{n\_fft}`, :attr:`window` will be padded on
      both sides to length :attr:`n_fft` before being applied.

    * If :attr:`center` is ``True`` (default), :attr:`input` will be padded on
      both sides so that the :math:`t`-th frame is centered at time
      :math:`t \times \text{hop\_length}`. Otherwise, the :math:`t`-th frame
      begins at time  :math:`t \times \text{hop\_length}`.

    * :attr:`pad_mode` determines the padding method used on :attr:`input` when
      :attr:`center` is ``True``. See :meth:`torch.nn.functional.pad` for
      all available options. Default is ``"reflect"``.

    * If :attr:`onesided` is ``True`` (default for real input), only values for
      :math:`\omega` in :math:`\left[0, 1, 2, \dots, \left\lfloor
      \frac{\text{n\_fft}}{2} \right\rfloor + 1\right]` are returned because
      the real-to-complex Fourier transform satisfies the conjugate symmetry,
      i.e., :math:`X[m, \omega] = X[m, \text{n\_fft} - \omega]^*`.
      Note if the input or window tensors are complex, then :attr:`onesided`
      output is not possible.

    * If :attr:`normalized` is ``True`` (default is ``False``), the function
      returns the normalized STFT results, i.e., multiplied by :math:`(\text{frame\_length})^{-0.5}`.

    * If :attr:`return_complex` is ``True`` (default if input is complex), the
      return is a ``input.dim() + 1`` dimensional complex tensor. If ``False``,
      the output is a ``input.dim() + 2`` dimensional real tensor where the last
      dimension represents the real and imaginary components.

    Returns either a complex tensor of size :math:`(* \times N \times T)` if
    :attr:`return_complex` is true, or a real tensor of size :math:`(* \times N
    \times T \times 2)`. Where :math:`*` is the optional batch size of
    :attr:`input`, :math:`N` is the number of frequencies where STFT is applied
    and :math:`T` is the total number of frames used.

    .. warning::
      This function changed signature at version 0.4.1. Calling with the
      previous signature may cause error or return incorrect result.

    Arguments:
        input (Tensor): the input tensor
        n_fft (int): size of Fourier transform
        hop_length (int, optional): the distance between neighboring sliding window
            frames. Default: ``None`` (treated as equal to ``floor(n_fft / 4)``)
        win_length (int, optional): the size of window frame and STFT filter.
            Default: ``None``  (treated as equal to :attr:`n_fft`)
        window (Tensor, optional): the optional window function.
            Default: ``None`` (treated as window of all :math:`1` s)
        center (bool, optional): whether to pad :attr:`input` on both sides so
            that the :math:`t`-th frame is centered at time :math:`t \times \text{hop\_length}`.
            Default: ``True``
        pad_mode (string, optional): controls the padding method used when
            :attr:`center` is ``True``. Default: ``"reflect"``
        normalized (bool, optional): controls whether to return the normalized STFT results
             Default: ``False``
        onesided (bool, optional): controls whether to return half of results to
            avoid redundancy for real inputs.
            Default: ``True`` for real :attr:`input` and :attr:`window`, ``False`` otherwise.
        return_complex (bool, optional): whether to return a complex tensor, or
            a real tensor with an extra last dimension for the real and
            imaginary components.

    Returns:
        Tensor: A tensor containing the STFT result with shape described above

    )re   rf   rg   rh   ri   rj   rk   rl   r	   é   rK   N)r1   r2   r3   r(   r)   r   r   r"   r7   r^   Úsizer;   ÚFÚpadÚviewrO   r   )rc   rd   re   rf   rg   rh   ri   rj   rk   rl   Z
signal_dimZextended_shaperp   r-   r-   r.   r"   Š  s     k
ýÿr"   )rc   rd   re   rf   rg   rh   rj   rk   Úlengthrl   r:   c
           
      C   s^   t j ¡ sBt| ƒturBt| fƒrBtt| f| |||||||||	d�S t | |||||||||	¡
S )a&  Inverse short time Fourier Transform. This is expected to be the inverse of :func:`~torch.stft`.
    It has the same parameters (+ additional optional parameter of :attr:`length`) and it should return the
    least squares estimation of the original signal. The algorithm will check using the NOLA condition (
    nonzero overlap).

    Important consideration in the parameters :attr:`window` and :attr:`center` so that the envelop
    created by the summation of all the windows is never zero at certain point in time. Specifically,
    :math:`\sum_{t=-\infty}^{\infty} |w|^2[n-t\times hop\_length] \cancel{=} 0`.

    Since :func:`~torch.stft` discards elements at the end of the signal if they do not fit in a frame,
    ``istft`` may return a shorter signal than the original signal (can occur if :attr:`center` is False
    since the signal isn't padded).

    If :attr:`center` is ``True``, then there will be padding e.g. ``'constant'``, ``'reflect'``, etc.
    Left padding can be trimmed off exactly because they can be calculated but right padding cannot be
    calculated without additional information.

    Example: Suppose the last window is:
    ``[17, 18, 0, 0, 0]`` vs ``[18, 0, 0, 0, 0]``

    The :attr:`n_fft`, :attr:`hop_length`, :attr:`win_length` are all the same which prevents the calculation
    of right padding. These additional values could be zeros or a reflection of the signal so providing
    :attr:`length` could be useful. If :attr:`length` is ``None`` then padding will be aggressively removed
    (some loss of signal).

    [1] D. W. Griffin and J. S. Lim, "Signal estimation from modified short-time Fourier transform,"
    IEEE Trans. ASSP, vol.32, no.2, pp.236-243, Apr. 1984.

    Arguments:
        input (Tensor): The input tensor. Expected to be output of :func:`~torch.stft`,
            can either be complex (``channel``, ``fft_size``, ``n_frame``), or real
            (``channel``, ``fft_size``, ``n_frame``, 2) where the ``channel``
            dimension is optional.
        n_fft (int): Size of Fourier transform
        hop_length (Optional[int]): The distance between neighboring sliding window frames.
            (Default: ``n_fft // 4``)
        win_length (Optional[int]): The size of window frame and STFT filter. (Default: ``n_fft``)
        window (Optional[torch.Tensor]): The optional window function.
            (Default: ``torch.ones(win_length)``)
        center (bool): Whether :attr:`input` was padded on both sides so that the :math:`t`-th frame is
            centered at time :math:`t \times \text{hop\_length}`.
            (Default: ``True``)
        normalized (bool): Whether the STFT was normalized. (Default: ``False``)
        onesided (Optional[bool]): Whether the STFT was onesided.
            (Default: ``True`` if ``n_fft != fft_size`` in the input size)
        length (Optional[int]): The amount to trim the signal by (i.e. the
            original signal length). (Default: whole signal)
        return_complex (Optional[bool]):
            Whether the output should be complex, or if the input should be
            assumed to derive from a real signal and window.
            Note that this is incompatible with ``onesided=True``.
            (Default: ``False``)

    Returns:
        Tensor: Least squares estimation of the original signal of size (..., signal_length)
    )re   rf   rg   rh   rj   rk   rr   rl   )	r1   r2   r3   r(   r)   r   r   r   r   )
rc   rd   re   rf   rg   rh   rj   rk   rr   rl   r-   r-   r.   r     s    =
ýÿr   )rc   ÚsortedÚreturn_inverseÚreturn_countsr7   r:   c              	   C   s~   t j ¡ s8t| ƒtur8t| fƒr8tt| f| ||||d�S |dur\tj	| ||||d�\}}}nt j
| |||d�\}}}|||fS )a 
  Returns the unique elements of the input tensor.

    .. note:: This function is different from :func:`torch.unique_consecutive` in the sense that
        this function also eliminates non-consecutive duplicate values.

    .. note:: Currently in the CUDA implementation and the CPU implementation when dim is specified,
        `torch.unique` always sort the tensor at the beginning regardless of the `sort` argument.
        Sorting could be slow, so if your input tensor is already sorted, it is recommended to use
        :func:`torch.unique_consecutive` which avoids the sorting.

    Arguments:
        input (Tensor): the input tensor
        sorted (bool): Whether to sort the unique elements in ascending order
            before returning as output.
        return_inverse (bool): Whether to also return the indices for where
            elements in the original input ended up in the returned unique list.
        return_counts (bool): Whether to also return the counts for each unique
            element.
        dim (int): the dimension to apply unique. If ``None``, the unique of the
            flattened input is returned. default: ``None``

    Returns:
        (Tensor, Tensor (optional), Tensor (optional)): A tensor or a tuple of tensors containing

            - **output** (*Tensor*): the output list of unique scalar elements.
            - **inverse_indices** (*Tensor*): (optional) if
              :attr:`return_inverse` is True, there will be an additional
              returned tensor (same shape as input) representing the indices
              for where elements in the original input map to in the output;
              otherwise, this function will only return a single tensor.
            - **counts** (*Tensor*): (optional) if
              :attr:`return_counts` is True, there will be an additional
              returned tensor (same shape as output or output.size(dim),
              if dim was specified) representing the number of occurrences
              for each unique value or tensor.

    Example::

        >>> output = torch.unique(torch.tensor([1, 3, 2, 3], dtype=torch.long))
        >>> output
        tensor([ 2,  3,  1])

        >>> output, inverse_indices = torch.unique(
                torch.tensor([1, 3, 2, 3], dtype=torch.long), sorted=True, return_inverse=True)
        >>> output
        tensor([ 1,  2,  3])
        >>> inverse_indices
        tensor([ 0,  2,  1,  2])

        >>> output, inverse_indices = torch.unique(
                torch.tensor([[1, 3], [2, 3]], dtype=torch.long), sorted=True, return_inverse=True)
        >>> output
        tensor([ 1,  2,  3])
        >>> inverse_indices
        tensor([[ 0,  2],
                [ 1,  2]])

    )rs   rt   ru   r7   N)rs   rt   ru   )r1   r2   r3   r(   r)   r   r   r$   r   Ú
unique_dimZ_unique2)rc   rs   rt   ru   r7   ÚoutputÚinverse_indicesÚcountsr-   r-   r.   Ú_unique_implZ  s*    =
þûürz   )rc   rt   ru   r7   r:   c                 C   sX   t j ¡ s6t| ƒtur6t| fƒr6tt| f| |||d�S tj| |||d�\}}}|||fS )a’  Eliminates all but the first element from every consecutive group of equivalent elements.

    .. note:: This function is different from :func:`torch.unique` in the sense that this function
        only eliminates consecutive duplicate values. This semantics is similar to `std::unique`
        in C++.

    Arguments:
        input (Tensor): the input tensor
        return_inverse (bool): Whether to also return the indices for where
            elements in the original input ended up in the returned unique list.
        return_counts (bool): Whether to also return the counts for each unique
            element.
        dim (int): the dimension to apply unique. If ``None``, the unique of the
            flattened input is returned. default: ``None``

    Returns:
        (Tensor, Tensor (optional), Tensor (optional)): A tensor or a tuple of tensors containing

            - **output** (*Tensor*): the output list of unique scalar elements.
            - **inverse_indices** (*Tensor*): (optional) if
              :attr:`return_inverse` is True, there will be an additional
              returned tensor (same shape as input) representing the indices
              for where elements in the original input map to in the output;
              otherwise, this function will only return a single tensor.
            - **counts** (*Tensor*): (optional) if
              :attr:`return_counts` is True, there will be an additional
              returned tensor (same shape as output or output.size(dim),
              if dim was specified) representing the number of occurrences
              for each unique value or tensor.

    Example::

        >>> x = torch.tensor([1, 1, 2, 2, 3, 1, 1, 2])
        >>> output = torch.unique_consecutive(x)
        >>> output
        tensor([1, 2, 3, 1, 2])

        >>> output, inverse_indices = torch.unique_consecutive(x, return_inverse=True)
        >>> output
        tensor([1, 2, 3, 1, 2])
        >>> inverse_indices
        tensor([0, 0, 1, 1, 2, 3, 3, 4])

        >>> output, counts = torch.unique_consecutive(x, return_counts=True)
        >>> output
        tensor([1, 2, 3, 1, 2])
        >>> counts
        tensor([2, 2, 1, 2, 1])
    )rt   ru   r7   )	r1   r2   r3   r(   r)   r   r   r%   r   )rc   rt   ru   r7   rw   rx   ry   r-   r-   r.   Ú_unique_consecutive_impl¯  s    4

þÿr{   c                 C   sN   t j ¡ s0t| ƒtur0t| fƒr0t| ||||ƒS t| ||||ƒ\}}}||fS r&   ©r1   r2   r3   r(   r)   r   rz   )rc   rs   rt   ru   r7   rw   Ú_ry   r-   r-   r.   Ú_return_countsí  s
    
r~   c                 C   sJ   t j ¡ s0t| ƒtur0t| fƒr0t| ||||ƒS t| ||||ƒ\}}}|S r&   r|   )rc   rs   rt   ru   r7   rw   r}   r-   r-   r.   Ú_return_outputø  s
    
r   c                 C   sN   t j ¡ s0t| ƒtur0t| fƒr0t| ||||ƒS t| ||||ƒ\}}}||fS r&   r|   )rc   rs   rt   ru   r7   rw   rx   r}   r-   r-   r.   Ú_return_inverse  s
    
r€   ru   rm   r$   )Zarg_nameZ	arg_indexÚdefaultÚif_trueÚif_falseÚmodule_nameÚ	func_namert   rK   c                 C   sJ   t j ¡ s.t| ƒtur.t| fƒr.t| |||ƒS t| |||ƒ\}}}||fS r&   ©r1   r2   r3   r(   r)   r   r{   )rc   rt   ru   r7   rw   r}   ry   r-   r-   r.   Ú_consecutive_return_counts.  s
    
r‡   c                 C   sF   t j ¡ s.t| ƒtur.t| fƒr.t| |||ƒS t| |||ƒ\}}}|S r&   r†   )rc   rt   ru   r7   rw   r}   r-   r-   r.   Ú_consecutive_return_output9  s
    
rˆ   c                 C   sJ   t j ¡ s.t| ƒtur.t| fƒr.t| |||ƒS t| |||ƒ\}}}||fS r&   r†   )rc   rt   ru   r7   rw   rx   r}   r-   r-   r.   Ú_consecutive_return_inverseD  s
    
r‰   r%   c                 C   sÊ   t j ¡ sDt| ƒtus"t|ƒturDt| |fƒrDtt| |f| ||d�S t|t	t
fƒsjt|t jƒrt| ¡ dkrt|\}}nFt|t jƒrˆ| ¡ }|dk ržtd|› �ƒ‚t	t| dƒƒ}t	t|ƒƒ}t | |||¡S )a  Returns a contraction of a and b over multiple dimensions.

    :attr:`tensordot` implements a generalized matrix product.

    Args:
      a (Tensor): Left tensor to contract
      b (Tensor): Right tensor to contract
      dims (int or tuple of two lists of integers): number of dimensions to
         contract or explicit lists of dimensions for :attr:`a` and
         :attr:`b` respectively

    When called with a non-negative integer argument :attr:`dims` = :math:`d`, and
    the number of dimensions of :attr:`a` and :attr:`b` is :math:`m` and :math:`n`,
    respectively, :func:`~torch.tensordot` computes

    .. math::
        r_{i_0,...,i_{m-d}, i_d,...,i_n}
          = \sum_{k_0,...,k_{d-1}} a_{i_0,...,i_{m-d},k_0,...,k_{d-1}} \times b_{k_0,...,k_{d-1}, i_d,...,i_n}.

    When called with :attr:`dims` of the list form, the given dimensions will be contracted
    in place of the last :math:`d` of :attr:`a` and the first :math:`d` of :math:`b`. The sizes
    in these dimensions must match, but :func:`~torch.tensordot` will deal with broadcasted
    dimensions.

    Examples::

        >>> a = torch.arange(60.).reshape(3, 4, 5)
        >>> b = torch.arange(24.).reshape(4, 3, 2)
        >>> torch.tensordot(a, b, dims=([1, 0], [0, 1]))
        tensor([[4400., 4730.],
                [4532., 4874.],
                [4664., 5018.],
                [4796., 5162.],
                [4928., 5306.]])

        >>> a = torch.randn(3, 4, 5, device='cuda')
        >>> b = torch.randn(4, 5, 6, device='cuda')
        >>> c = torch.tensordot(a, b, dims=2).cpu()
        tensor([[ 8.3504, -2.5436,  6.2922,  2.7556, -1.0732,  3.2741],
                [ 3.3161,  0.0704,  5.0187, -0.4079, -4.3126,  4.8744],
                [ 0.8223,  3.9445,  3.2168, -0.2400,  3.4117,  1.7780]])

    )Údimsr	   r   z*tensordot expects dims >= 0, but got dims=)r1   r2   r3   r(   r)   r   r   r#   r]   r^   r_   ZnumelÚitemÚRuntimeErrorr<   r   )ÚaÚbrŠ   Zdims_aZdims_br-   r-   r.   r#   o  s     ,
$
ÿ
ÿ
r#   c                  G   s@   t j ¡ s6tdd„ | D ƒƒr6t| ƒr6tt| g| ¢R Ž S t | ¡S )aL  Do cartesian product of the given sequence of tensors. The behavior is similar to
    python's `itertools.product`.

    Arguments:
        *tensors: any number of 1 dimensional tensors.

    Returns:
        Tensor: A tensor equivalent to converting all the input tensors into lists,
            do `itertools.product` on these lists, and finally convert the resulting list
            into tensor.

    Example::

        >>> a = [1, 2, 3]
        >>> b = [4, 5]
        >>> list(itertools.product(a, b))
        [(1, 4), (1, 5), (2, 4), (2, 5), (3, 4), (3, 5)]
        >>> tensor_a = torch.tensor(a)
        >>> tensor_b = torch.tensor(b)
        >>> torch.cartesian_prod(tensor_a, tensor_b)
        tensor([[1, 4],
                [1, 5],
                [2, 4],
                [2, 5],
                [3, 4],
                [3, 5]])
    c                 s   s   | ]}t |ƒtuV  qd S r&   r'   r*   r-   r-   r.   r/   Ç  r0   z!cartesian_prod.<locals>.<genexpr>)r1   r2   r3   r4   r   r   r   r   r5   r-   r-   r.   r   ª  s    
r   c                  G   s:   t dd„ | D ƒƒr,t| ƒr,tt| g| ¢R Ž S tjj | ¡S )aS  Create a block diagonal matrix from provided tensors.

    Arguments:
        *tensors: One or more tensors with 0, 1, or 2 dimensions.

    Returns:
        Tensor: A 2 dimensional tensor with all the input tensors arranged in
            order such that their upper left and lower right corners are
            diagonally adjacent. All other elements are set to 0.

    Example::

        >>> import torch
        >>> A = torch.tensor([[0, 1], [1, 0]])
        >>> B = torch.tensor([[3, 4, 5], [6, 7, 8]])
        >>> C = torch.tensor(7)
        >>> D = torch.tensor([1, 2, 3])
        >>> E = torch.tensor([[4], [5], [6]])
        >>> torch.block_diag(A, B, C, D, E)
        tensor([[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
                [1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 3, 4, 5, 0, 0, 0, 0, 0],
                [0, 0, 6, 7, 8, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 7, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 1, 2, 3, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0, 4],
                [0, 0, 0, 0, 0, 0, 0, 0, 0, 5],
                [0, 0, 0, 0, 0, 0, 0, 0, 0, 6]])
    c                 s   s   | ]}t |ƒtuV  qd S r&   r'   r*   r-   r-   r.   r/   é  r0   zblock_diag.<locals>.<genexpr>)r4   r   r   r   r1   Z_CZ_VariableFunctionsr5   r-   r-   r.   r   Ë  s    r   ç       @Ú#use_mm_for_euclid_dist_if_necessaryc                 C   s    t j ¡ sFt| ƒtus"t|ƒturFt| |fƒrFtt| |f| |||d�S |dkr^t | ||d¡S |dkrvt | ||d¡S |dkrŽt | ||d¡S t	|› d�ƒ‚dS )	a‰  Computes batched the p-norm distance between each pair of the two collections of row vectors.

    Args:
        x1 (Tensor): input tensor of shape :math:`B \times P \times M`.
        x2 (Tensor): input tensor of shape :math:`B \times R \times M`.
        p: p value for the p-norm distance to calculate between each vector pair
            :math:`\in [0, \infty]`.
        compute_mode:
            'use_mm_for_euclid_dist_if_necessary' - will use matrix multiplication approach to calculate
            euclidean distance (p = 2) if P > 25 or R > 25
            'use_mm_for_euclid_dist' - will always use matrix multiplication approach to calculate
            euclidean distance (p = 2)
            'donot_use_mm_for_euclid_dist' - will never use matrix multiplication approach to calculate
            euclidean distance (p = 2)
            Default: use_mm_for_euclid_dist_if_necessary.

    If x1 has shape :math:`B \times P \times M` and x2 has shape :math:`B \times R \times M` then the
    output will have shape :math:`B \times P \times R`.

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

    Example:

        >>> a = torch.tensor([[0.9041,  0.0196], [-0.3108, -2.4423], [-0.4821,  1.059]])
        >>> a
        tensor([[ 0.9041,  0.0196],
                [-0.3108, -2.4423],
                [-0.4821,  1.0590]])
        >>> b = torch.tensor([[-2.1763, -0.4713], [-0.6986,  1.3702]])
        >>> b
        tensor([[-2.1763, -0.4713],
                [-0.6986,  1.3702]])
        >>> torch.cdist(a, b, p=2)
        tensor([[3.1193, 2.0959],
                [2.7138, 3.8322],
                [2.2830, 0.3791]])
    )ÚpÚcompute_moder�   NZuse_mm_for_euclid_distr	   Zdonot_use_mm_for_euclid_distrK   z& is not a valid value for compute_mode)
r1   r2   r3   r(   r)   r   r   r   r   Ú
ValueError)Úx1Zx2r‘   r’   r-   r-   r.   r   î  s    *
$ÿr   c                  G   sT   t j ¡ s6tdd„ | D ƒƒr6t| ƒr6tt| g| ¢R Ž S t| ƒdkrJ| d } t | ¡S )a§  
    Returns a 1-dimensional view of each input tensor with zero dimensions.
    Input tensors with one or more dimensions are returned as-is.

    Args:
        input (Tensor or list of Tensors)

    Returns:
        output (Tensor or tuple of Tensors)

    Example::
        >>> x = torch.randn(2)
        >>> x
        tensor([1.4584, 0.7583])
        >>> torch.atleast_1d(x)
        tensor([1.4584, 0.7583])
        >>> x = torch.tensor(1.)
        >>> x
        tensor(1.)
        >>> torch.atleast_1d(x)
        tensor([1.])
        >>> x = torch.tensor(0.5)
        >>> y = torch.tensor(1.)
        >>> torch.atleast_1d((x,y))
        (tensor([0.5000]), tensor([1.]))
    c                 s   s   | ]}t |ƒtuV  qd S r&   r'   r*   r-   r-   r.   r/   A  r0   zatleast_1d.<locals>.<genexpr>r	   r   )	r1   r2   r3   r4   r   r   r   r\   r   r5   r-   r-   r.   r   %  s    
r   c                  G   sT   t j ¡ s6tdd„ | D ƒƒr6t| ƒr6tt| g| ¢R Ž S t| ƒdkrJ| d } t | ¡S )aû  
    Returns a 2-dimensional view of each each input tensor with zero dimensions.
    Input tensors with two or more dimensions are returned as-is.
    Args:
        input (Tensor or list of Tensors)

    Returns:
        output (Tensor or tuple of Tensors)

    Example::
        >>> x = torch.tensor(1.)
        >>> x
        tensor(1.)
        >>> torch.atleast_2d(x)
        tensor([[1.]])
        >>> x = torch.randn(2,2)
        >>> x
        tensor([[2.2086, 2.5165],
                [0.1757, 0.5194]])
        >>> torch.atleast_2d(x)
        tensor([[2.2086, 2.5165],
                [0.1757, 0.5194]])
        >>> x = torch.tensor(0.5)
        >>> y = torch.tensor(1.)
        >>> torch.atleast_2d((x,y))
        (tensor([[0.5000]]), tensor([[1.]]))
    c                 s   s   | ]}t |ƒtuV  qd S r&   r'   r*   r-   r-   r.   r/   d  r0   zatleast_2d.<locals>.<genexpr>r	   r   )	r1   r2   r3   r4   r   r   r   r\   r   r5   r-   r-   r.   r   G  s    
r   c                  G   sT   t j ¡ s6tdd„ | D ƒƒr6t| ƒr6tt| g| ¢R Ž S t| ƒdkrJ| d } t | ¡S )aå  
    Returns a 3-dimensional view of each each input tensor with zero dimensions.
    Input tensors with three or more dimensions are returned as-is.
    Args:
        input (Tensor or list of Tensors)

    Returns:
        output (Tensor or tuple of Tensors)

    Example:

        >>> x = torch.tensor(0.5)
        >>> x
        tensor(0.5000)
        >>> torch.atleast_3d(x)
        tensor([[[0.5000]]])
        >>> y = torch.randn(2,2)
        >>> y
        tensor([[-0.8079,  0.7460],
                [-1.1647,  1.4734]])
        >>> torch.atleast_3d(y)
        tensor([[[-0.8079],
                [ 0.7460]],
                <BLANKLINE>
                [[-1.1647],
                [ 1.4734]]])
        >>> x = torch.randn(1,1,1)
        >>> x
        tensor([[[-1.5689]]])
        >>> torch.atleast_3d(x)
        tensor([[[-1.5689]]])
        >>> x = torch.tensor(0.5)
        >>> y = torch.tensor(1.)
        >>> torch.atleast_3d((x,y))
        (tensor([[[0.5000]]]), tensor([[[1.]]]))
    c                 s   s   | ]}t |ƒtuV  qd S r&   r'   r*   r-   r-   r.   r/   �  r0   zatleast_3d.<locals>.<genexpr>r	   r   )	r1   r2   r3   r4   r   r   r   r\   r   r5   r-   r-   r.   r   j  s    %
r   Úfroc                 C   s   d S r&   r-   ©rc   r‘   r7   ÚkeepdimrC   rM   r-   r-   r.   r   ¦  s    r   c                 C   s   d S r&   r-   r–   r-   r-   r.   r   «  s    c                 C   s   d S r&   r-   r–   r-   r-   r.   r   °  s    c                 C   s   d S r&   r-   r–   r-   r-   r.   r   µ  s    c              
   C   sb  t j ¡ s:t| ƒtur:t| fƒr:tt| f| |||||d�S |  ¡ }|du r²|du r²|du r²|dur²t	|t
ƒr„|dkr„tj| d|d�S t	|t
ƒs²dd„ t|ƒD ƒ}tj| |||d�S |durÒt	|tƒrÌ|g}qÖ|}nd}t	|t
ƒ�rÒ|dk�rF|durütdƒ‚|du �rd	d„ t|ƒD ƒ}|du �r2tj| ||d
�S tj| |||d�S n||dk�rÂ|du�rbtdƒ‚|du �r–|du �r„tj| |d
�S tj| ||d�S n,|du �r°tj| ||d
�S tj| |||d�S td|› �ƒ‚nŒ|du �rîdd„ t|ƒD ƒ}|du �r*|du �rtj| |||d
�S tj| ||||d�S n4|du �rHtj| ||||d�S tj| |||||d�S dS )aÛ  Returns the matrix norm or vector norm of a given tensor.

    .. warning::

        torch.norm is deprecated and may be removed in a future PyTorch release.
        Use :func:`torch.linalg.norm` instead, but note that :func:`torch.linalg.norm`
        has a different signature and slightly different behavior that is
        more consistent with NumPy's numpy.linalg.norm.

    Args:
        input (Tensor): the input tensor
        p (int, float, inf, -inf, 'fro', 'nuc', optional): the order of norm. Default: ``'fro'``
            The following norms can be calculated:

            =====  ============================  ==========================
            ord    matrix norm                   vector norm
            =====  ============================  ==========================
            None   Frobenius norm                2-norm
            'fro'  Frobenius norm                --
            'nuc'  nuclear norm                  --
            Other  as vec norm when dim is None  sum(abs(x)**ord)**(1./ord)
            =====  ============================  ==========================

        dim (int, 2-tuple of ints, 2-list of ints, optional): If it is an int,
            vector norm will be calculated, if it is 2-tuple of ints, matrix norm
            will be calculated. If the value is None, matrix norm will be calculated
            when the input tensor only has two dimensions, vector norm will be
            calculated when the input tensor only has one dimension. If the input
            tensor has more than two dimensions, the vector norm will be applied to
            last dimension.
        keepdim (bool, optional): whether the output tensors have :attr:`dim`
            retained or not. Ignored if :attr:`dim` = ``None`` and
            :attr:`out` = ``None``. Default: ``False``
        out (Tensor, optional): the output tensor. Ignored if
            :attr:`dim` = ``None`` and :attr:`out` = ``None``.
        dtype (:class:`torch.dtype`, optional): the desired data type of
            returned tensor. If specified, the input tensor is casted to
            :attr:'dtype' while performing the operation. Default: None.


    Example::

        >>> import torch
        >>> a = torch.arange(9, dtype= torch.float) - 4
        >>> b = a.reshape((3, 3))
        >>> torch.norm(a)
        tensor(7.7460)
        >>> torch.norm(b)
        tensor(7.7460)
        >>> torch.norm(a, float('inf'))
        tensor(4.)
        >>> torch.norm(b, float('inf'))
        tensor(4.)
        >>> c = torch.tensor([[ 1, 2, 3],[-1, 1, 4]] , dtype= torch.float)
        >>> torch.norm(c, dim=0)
        tensor([1.4142, 2.2361, 5.0000])
        >>> torch.norm(c, dim=1)
        tensor([3.7417, 4.2426])
        >>> torch.norm(c, p=1, dim=1)
        tensor([6., 6.])
        >>> d = torch.arange(8, dtype= torch.float).reshape(2,2,2)
        >>> torch.norm(d, dim=(1,2))
        tensor([ 3.7417, 11.2250])
        >>> torch.norm(d[0, :, :]), torch.norm(d[1, :, :])
        (tensor(3.7417), tensor(11.2250))
    )r‘   r7   r—   rC   rM   Nr•   r-   )r7   r—   c                 S   s   g | ]}|‘qS r-   r-   rN   r-   r-   r.   rF     r0   znorm.<locals>.<listcomp>z1dtype argument is not supported in frobenius normc                 S   s   g | ]}|‘qS r-   r-   rN   r-   r-   r.   rF      r0   )r—   )r—   rC   Znucz/dtype argument is not supported in nuclear normz4only valid string values are 'fro' and 'nuc', found c                 S   s   g | ]}|‘qS r-   r-   rN   r-   r-   r.   rF   5  r0   )r—   rM   )r—   rM   rC   )r1   r2   r3   r(   r)   r   r   r   r7   r]   Ústrr   Zfrobenius_normr<   r;   r“   Znuclear_normrŒ   )rc   r‘   r7   r—   rC   rM   ÚndimZ_dimr-   r-   r.   r   »  s^    D
ÿ 














c                  G   s@   t j ¡ s6tdd„ | D ƒƒr6t| ƒr6tt| g| ¢R Ž S t | ¡S )aR  Returns the matrix product of the :math:`N` 2-D tensors. This product is efficiently computed
    using the matrix chain order algorithm which selects the order in which incurs the lowest cost in terms
    of arithmetic operations (`[CLRS]`_). Note that since this is a function to compute the product, :math:`N`
    needs to be greater than or equal to 2; if equal to 2 then a trivial matrix-matrix product is returned.
    If :math:`N` is 1, then this is a no-op - the original matrix is returned as is.


    Args:
        matrices (Tensors...): a sequence of 2 or more 2-D tensors whose product is to be determined.


    Returns:
        Tensor: if the :math:`i^{th}` tensor was of dimensions :math:`p_{i} \times p_{i + 1}`, then the product
        would be of dimensions :math:`p_{1} \times p_{N + 1}`.

    Example::

        >>> a = torch.randn(3, 4)
        >>> b = torch.randn(4, 5)
        >>> c = torch.randn(5, 6)
        >>> d = torch.randn(6, 7)
        >>> torch.chain_matmul(a, b, c, d)
        tensor([[ -2.3375,  -3.9790,  -4.1119,  -6.6577,   9.5609, -11.5095,  -3.2614],
                [ 21.4038,   3.3378,  -8.4982,  -5.2457, -10.2561,  -2.4684,   2.7163],
                [ -0.9647,  -5.8917,  -2.3213,  -5.2284,  12.8615, -12.2816,  -2.5095]])

    .. _`[CLRS]`: https://mitpress.mit.edu/books/introduction-algorithms-third-edition
    c                 s   s   | ]}t |ƒtuV  qd S r&   r'   r*   r-   r-   r.   r/   `  r0   zchain_matmul.<locals>.<genexpr>)r1   r2   r3   r4   r   r   r   r   )Zmatricesr-   r-   r.   r   B  s    
r   c                 C   s   t j| || d�S )a3  Computes the LU factorization of a matrix or batches of matrices
    :attr:`A`. Returns a tuple containing the LU factorization and
    pivots of :attr:`A`.  Pivoting is done if :attr:`pivot` is set to
    ``True``.

    .. note::
        The pivots returned by the function are 1-indexed. If :attr:`pivot` is ``False``,
        then the returned pivots is a tensor filled with zeros of the appropriate size.

    .. note::
        LU factorization with :attr:`pivot` = ``False`` is not available for CPU, and attempting
        to do so will throw an error. However, LU factorization with :attr:`pivot` = ``False`` is
        available for CUDA.

    .. note::
        This function does not check if the factorization was successful or not if
        :attr:`get_infos` is ``True`` since the status of the factorization is present in the
        third element of the return tuple.

    .. note::
        In the case of batches of square matrices with size less or
        equal to 32 on a CUDA device, the LU factorization is repeated
        for singular matrices due to the bug in the MAGMA library (see
        magma issue 13).

    .. note::
       ``L``, ``U``, and ``P`` can be derived using :func:`torch.lu_unpack`.

    Arguments:
        A (Tensor): the tensor to factor of size :math:`(*, m, n)`
        pivot (bool, optional): controls whether pivoting is done. Default: ``True``
        get_infos (bool, optional): if set to ``True``, returns an info IntTensor.
                                    Default: ``False``
        out (tuple, optional): optional output tuple. If :attr:`get_infos` is ``True``,
                               then the elements in the tuple are Tensor, IntTensor,
                               and IntTensor. If :attr:`get_infos` is ``False``, then the
                               elements in the tuple are Tensor, IntTensor. Default: ``None``

    Returns:
        (Tensor, IntTensor, IntTensor (optional)): A tuple of tensors containing

            - **factorization** (*Tensor*): the factorization of size :math:`(*, m, n)`

            - **pivots** (*IntTensor*): the pivots of size :math:`(*, m)`

            - **infos** (*IntTensor*, *optional*): if :attr:`get_infos` is ``True``, this is a tensor of
              size :math:`(*)` where non-zero values indicate whether factorization for the matrix or
              each minibatch has succeeded or failed

    Example::

        >>> A = torch.randn(2, 3, 3)
        >>> A_LU, pivots = torch.lu(A)
        >>> A_LU
        tensor([[[ 1.3506,  2.5558, -0.0816],
                 [ 0.1684,  1.1551,  0.1940],
                 [ 0.1193,  0.6189, -0.5497]],

                [[ 0.4526,  1.2526, -0.3285],
                 [-0.7988,  0.7175, -0.9701],
                 [ 0.2634, -0.9255, -0.3459]]])
        >>> pivots
        tensor([[ 3,  3,  3],
                [ 3,  3,  3]], dtype=torch.int32)
        >>> A_LU, pivots, info = torch.lu(A, get_infos=True)
        >>> if info.nonzero().size(0) == 0:
        ...   print('LU factorization succeeded for all samples!')
        LU factorization succeeded for all samples!
    )ÚpivotZcheck_errors)r1   Z_lu_with_info)ÚArš   Ú	get_infosrC   r-   r-   r.   Ú_lu_imple  s    Hr�   )Úout_lenrœ   rC   r:   c                 C   sZ   |rdnd}| | dkr4t ddt|ƒ › d| › �ƒ‚t|ttfƒsVt dt|ƒj› �ƒ‚d S )Nr	   r   rK   zexpected tuple of z elements but got z-argument 'out' must be tuple of Tensors, not )Ú	TypeErrorr;   r]   r_   r^   r(   Ú__name__)rž   rœ   rC   Zget_infos_intr-   r-   r.   Ú_check_list_sizeµ  s
    r¡   c                 C   s–   t j ¡ s6t| ƒtur6t| fƒr6tt| f| |||d�S t| |||ƒ}|d urŽt	t
|ƒ||ƒ tt
|ƒƒD ] }||  || ¡ || ¡ qh|S |S d S )N©rš   rœ   rC   ©r1   r2   r3   r(   r)   r   r   r   r�   r¡   r\   r<   Z
resize_as_rT   ©r›   rš   rœ   rC   r>   rA   r-   r-   r.   Ú_lu_with_infos¼  s    
ÿr¥   c                 C   s¢   t j ¡ s6t| ƒtur6t| fƒr6tt| f| |||d�S t| |||ƒ}|d urŽt	t
|ƒ||ƒ tt
|ƒƒD ] }||  || ¡ || ¡ qh|S |d |d fS d S )Nr¢   r   r	   r£   r¤   r-   r-   r.   Ú_lu_no_infosË  s    
ÿr¦   rœ   r   c                  G   s   t dƒ‚d S )Nz$`align_tensors` not yet implemented.)rŒ   r5   r-   r-   r.   r   ç  s    r   )r   )TT)NNNTrb   FNN)NNNTFNNF)TFFN)FFN)TFFN)TFFN)TFFN)FFN)FFN)FFN)rK   )r�   r�   )r•   NFNN)r•   NFNN)r•   NFNN)r•   NFNN)r•   NFNN)TFN)TFN)TFN)LÚtypingr   r   r   r   r   r   r1   Ztorch.nn.functionalÚnnZ
functionalro   Ztorch.typesr   Z_lowrankr
   r   Z	overridesr   r   Z_jit_internalr   r   r   Úoverloadr)   r   Ú__all__r   r!   Z_Indicesr;   rB   rE   r   r   r    ra   Úboolr˜   r"   r   rv   Z_unique_impl_outrz   r{   r~   r   r€   r    Z_return_inverse_falseZ_return_inverse_truer$   Ú__doc__r‡   rˆ   r‰   Z!_consecutive_return_inverse_falseZ _consecutive_return_inverse_truer%   r#   r   r   r   r   r   r   r   r   r�   Z
_ListOrSeqr¡   r¥   r¦   r   r   r-   r-   r-   r.   Ú<module>   sF    
2
nV&&     üü|     üüH   þþU   þþ>


ù	ùù


ù	ùù
;!#
7"#-
 #
K


ù