a
    Ž¥»a ¤  ã                   @   s¼  d dl Zd dlZd dlZd dlmZmZmZmZm	Z	m
Z
mZmZmZmZ d dlmZ d dlZd dlmZ ddlmZ dgZG dd	„ d	e	ƒZejd
ejdejdejdejd
ejdejdiZeeee e f dœdd„Z!ede
e f ede
e f dœdd„Z"ede
e f ede
e f dœdd„Z#ede
e f ede
e f dœdd„Z$ee
e dœdd„Z%dddddœeee&e&e&e&e
e dœd d!„Z'eeeeef dœd"d#„Z(eeee e ed$œd%d&„Z)dd'œeeee
ee*ee*ge*f f  e*d(œd)d*„Z+ej,ej,d+œd,d-„Z-e$e"e#eee e e&e
ee*eeeege*f f  e
e d.œd/d0„ƒƒƒZ.ddd1ddddd2œeee
e  e
e  e&e&e&e&e&ee*eeeege*f f e
e d3œd4d5„Z/G d6d7„ d7e	ƒZ0d8Z1d9Z2ee0eef ee
e d:œd;d<„Z3eee
e e
e f d=œd>d?„Z4eee&e
e d@œdAdB„Z5eee&ee
e e
e0 f d@œdCdD„Z6eee&ee
e e
ee0eef  f d@œdEdF„Z7dddd1ddd1dddGœ	eee&e
e  e
e  e&e&e&e&e&e
ee*eeeege*f f  ddHœdId„Z8dS )Jé    N)
ÚAnyÚCallableÚDictÚListÚ
NamedTupleÚOptionalÚTupleÚTypeÚUnionÚcast)ÚSimpleNamespace)ÚTensoré   )Ú_unravel_indexÚassert_closec                   @   sD   e Zd ZU ee ed< eed< deed dœdd„Zedœdd	„Zd
S )Ú_TestingErrorMetaÚtypeÚmsgÚ )ÚprefixÚpostfixÚreturnc                 C   s   | j |› | j› |› �d�S )N)r   )Ú_replacer   )Úselfr   r   © r   úP/home/yuhw/wc/pochoir/venv/lib/python3.9/site-packages/torch/testing/_asserts.pyÚ	amend_msg   s    z_TestingErrorMeta.amend_msg)r   c                 C   s   |   | j¡S ©N)r   r   )r   r   r   r   Úto_error   s    z_TestingErrorMeta.to_errorN)r   r   )	Ú__name__Ú
__module__Ú__qualname__r	   Ú	ExceptionÚ__annotations__Ústrr   r   r   r   r   r   r      s   
r   )gü©ñÒMbP?çñhãˆµøä>)gü©ñÒMb�?r%   )gkN¹uÏµ>r%   )çH¯¼šò×z>r&   )ÚactualÚexpectedr   c                 C   s8   t  | jd¡\}}t  |jd¡\}}t||ƒt||ƒfS )N©ç        r*   )Ú_DTYPE_PRECISIONSÚgetÚdtypeÚmax)r'   r(   Zactual_rtolZactual_atolZexpected_rtolZexpected_atolr   r   r   Ú_get_default_rtol_and_atol)   s    r/   .)Úcheck_tensorsr   c                    sH   t  ˆ ¡dtttttttttgtf f  ttt	 dœ‡ fdd„ƒ}|S )a  Decorates strided tensor check functions to individually handle sparse COO members.

    If the inputs are not sparse COO, this decorator is a no-op.

    Args:
        check_tensors (Callable[[Tensor, Tensor], Optional[Exception]]): Tensor check function for strided tensors.
    N©r'   r(   r   Úkwargsr   c                    sÄ   | j sˆ | |fd|i|¤ŽS |  ¡ | ¡ krJttd|  ¡ › d| ¡ › �ƒS t|ddd�}ˆ |  ¡ | ¡ fd|pztjtdd�i|¤Ž}|rŒ|S ˆ |  	¡ | 	¡ fd|p®tjtdd�i|¤Ž}|rÀ|S d S )	Nr   zEThe number of specified values in sparse COO tensors does not match: ú != r   ©ÚrtolÚatolzSparse COO indices©Ú
identifierzSparse COO values)
Ú	is_sparseZ_nnzr   ÚAssertionErrorÚdictZ_indicesÚ	functoolsÚpartialÚ_make_mismatch_msgZ_values©r'   r(   r   r2   Zkwargs_equalÚ
error_meta©r0   r   r   Úwrapper:   sB    ÿÿýþýüþýüz7_check_sparse_coo_members_individually.<locals>.wrapper)N©
r<   Úwrapsr   r   r
   r$   r   ÚDiagnosticsr   r   ©r0   rB   r   rA   r   Ú&_check_sparse_coo_members_individually/   s     ýû'rG   c                    sH   t  ˆ ¡dtttttttttgtf f  ttt	 dœ‡ fdd„ƒ}|S )a!  Decorates strided tensor check functions to individually handle sparse CSR members.

    If the inputs are not sparse CSR, this decorator is a no-op.

    Args:
        check_tensors (Callable[[Tensor, Tensor], Optional[Exception]]): Tensor check function for strided
        tensors.
    Nr1   c                    sÊ   | j sˆ | |fd|i|¤ŽS t|ddd�}ˆ |  ¡ | ¡ fd|pLtjtdd�i|¤Ž}|r^|S ˆ |  ¡ | ¡ fd|p€tjtdd�i|¤Ž}|r’|S ˆ |  ¡ | ¡ fd|p´tjtdd�i|¤Ž}|rÆ|S d S )Nr   r   r4   zSparse CSR crow_indicesr7   zSparse CSR col_indiceszSparse CSR values)Zis_sparse_csrr;   Zcrow_indicesr<   r=   r>   Zcol_indicesÚvaluesr?   rA   r   r   rB   q   sD    þýüþýüþýüz7_check_sparse_csr_members_individually.<locals>.wrapper)NrC   rF   r   rA   r   Ú&_check_sparse_csr_members_individuallye   s     ýû'rI   )Úcheck_tensor_valuesr   c                    s*   t  ˆ ¡ttttt dœ‡ fdd„ƒ}|S )an  Decorates non-quantized tensor check functions to handle quantized tensors.

    If the inputs are not quantized, this decorator is a no-op.

    Args:
        check_tensor_values (Callable[..., Optional[_TestingErrorMeta]]): Tensor check function for continuous tensors.

    Returns:
        Optional[_TestingErrorMeta]: Return value of :attr:`check_tensors`.
    )r'   r(   r2   r   c                    s2   | j sˆ | |fi |¤ŽS ˆ |  ¡ | ¡ fi |¤ŽS r   )Úis_quantizedZ
dequantize)r'   r(   r2   ©rJ   r   r   rB   ª   s    z!_check_quantized.<locals>.wrapper)r<   rD   r   r   r   r   )rJ   rB   r   rL   r   Ú_check_quantizedœ   s    rM   )Úinputr   c                 C   s,   | j tjtjtjhvr(ttd| j › �ƒS dS )z‘Checks if the tensor is supported by the current infrastructure.

    Returns:
        (Optional[_TestingErrorMeta]): If check did not pass.
    zUnsupported tensor layout N)ÚlayoutÚtorchÚstridedÚ
sparse_cooZ
sparse_csrr   Ú
ValueError)rN   r   r   r   Ú_check_supported_tensor´   s    rT   T©Úcheck_deviceÚcheck_dtypeÚcheck_strideÚcheck_is_coalesced)r'   r(   rV   rW   rX   rY   r   c                C   sx  d}| j |j kr(tt| d| j |j ¡ƒS | j|jkrLtt| d| j|j¡ƒS | jtjkrˆ|rˆ|  ¡ | ¡ krˆtt| d|  ¡ | ¡ ¡ƒS | jtjkrÄ|rÄ|  	¡ | 	¡ krÄtt| d|  	¡ | 	¡ ¡ƒS |rì| j
|j
krìtt| d| j
|j
¡ƒS | j|jk�rtt| d| j|j¡ƒS | j�rH|  ¡ | ¡ k�rHtt| d|  ¡ | ¡ ¡ƒS |�rt| j|jk�rttt| d	| j|j¡ƒS d
S )a¸  Checks if the attributes of two tensors match.

    Always checks the :attr:`~torch.Tensor.shape` and :attr:`~torch.Tensor.layout`. Checks for
    :attr:`~torch.Tensor.device`, :attr:`~torch.Tensor.dtype`, :meth:`~torch.Tensor.stride` if the tensors are strided,
    and :meth:`~torch.tensor.is_coalesced` if the tensors are sparse COO are optional and can be disabled.

    Args:
        actual (Tensor): Actual tensor.
        expected (Tensor): Expected tensor.
        check_device (bool): If ``True`` (default), checks that both :attr:`actual` and :attr:`expected` are on the
            same :attr:`~torch.Tensor.device`.
        check_dtype (bool): If ``True`` (default), checks that both :attr:`actual` and :attr:`expected` have the same
            ``dtype``.
        check_stride (bool): If ``True`` (default) and the tensors are strided, checks that both :attr:`actual` and
            :attr:`expected` have the same stride.
        check_is_coalesced (bool): If ``True`` (default) and the tensors are sparse COO, checks that both
            :attr:`actual` and :attr:`expected` are either coalesced or uncoalesced.

    Returns:
        (Optional[_TestingErrorMeta]): If checks did not pass.
    z5The values for attribute '{}' do not match: {} != {}.ÚshaperO   zstride()zis_coalesced()ÚdevicerK   z	qscheme()r-   N)rZ   r   r:   ÚformatrO   rP   rQ   ZstriderR   Úis_coalescedr[   rK   Zqschemer-   )r'   r(   rV   rW   rX   rY   Ú
msg_fmtstrr   r   r   Ú_check_attributes_equalÀ   s,      ÿÿr_   c                 C   sz   | j |j kr|  ¡ } | ¡ }| j|jkrLt | j|j¡}|  |¡} | |¡}| jrr|  ¡ | ¡ krr|  ¡ } | ¡ }| |fS )aç  Equalizes some attributes of two tensors for value comparison.

    If :attr:`actual` and :attr:`expected`
    - are not on the same :attr:`~torch.Tensor.device`, they are moved CPU memory, and
    - do not have the same ``dtype``, they are promoted  to a common ``dtype`` (according to
        :func:`torch.promote_types`)

    Args:
        actual (Tensor): Actual tensor.
        expected (Tensor): Expected tensor.

    Returns:
        Tuple(Tensor, Tensor): Equalized tensors.
    )	r[   Úcpur-   rP   Zpromote_typesÚtor9   r]   Zcoalesce)r'   r(   r-   r   r   r   Ú_equalize_attributesü   s    

rb   )r'   r(   Ú
mismatchesr5   r6   r   c             
   C   sº   |  ¡ }t |¡ ¡ }|  ¡ }| ¡ }| ¡  }	t || ¡}
d|
|	< t |
d¡\}}|
t |¡ }d||	< t |d¡\}}t|tt	|ƒ| ¡ t
| ¡ |jƒ|| ¡ t
| ¡ |jƒ|d�S )aµ  Traces mismatches and returns diagnostic information.

    Args:
        actual (Tensor): Actual tensor.
        expected (Tensor): Expected tensor.
        mismatches (Tensor): Boolean mask of the same shape as :attr:`actual` and :attr:`expected` that indicates
            the location of mismatches.

    Returns:
        (Diagnostics): Mismatch diagnostics with the following attributes:

            - ``number_of_elements`` (int): Number of elements in each tensor being compared.
            - ``total_mismatches`` (int): Total number of mismatches.
            - ``max_abs_diff`` (Union[int, float]): Greatest absolute difference of the inputs.
            - ``max_abs_diff_idx`` (Union[int, Tuple[int, ...]]): Index of greatest absolute difference.
            - ``atol`` (float): Allowed absolute tolerance.
            - ``max_rel_diff`` (Union[int, float]): Greatest relative difference of the inputs.
            - ``max_rel_diff_idx`` (Union[int, Tuple[int, ...]]): Index of greatest relative difference.
            - ``rtol`` (float): Allowed relative tolerance.

            For ``max_abs_diff`` and ``max_rel_diff`` the type depends on the :attr:`~torch.Tensor.dtype` of the inputs.
    r   )Únumber_of_elementsÚtotal_mismatchesÚmax_abs_diffÚmax_abs_diff_idxr6   Úmax_rel_diffÚmax_rel_diff_idxr5   )ZnumelrP   ÚsumÚitemÚflattenÚabsr.   rE   r   Úintr   rZ   )r'   r(   rc   r5   r6   rd   re   Za_flatZb_flatZmatches_flatZabs_diffrf   Zmax_abs_diff_flat_idxZrel_diffrh   Zmax_rel_diff_flat_idxr   r   r   Ú_trace_mismatches  s*    
øro   r7   )r'   r(   Údiagnosticsr8   r   c                   sô   |   ¡ t g ¡k‰|jdko$|jdk‰ tttttdf ttdœ‡ ‡fdd„}ˆrTdnd}|d u rf|}nt	|ƒrv||ƒ}|› dˆ r„d	nd
› d�}ˆs¼|d|j
› d|j› d|j
|j d›d�7 }||d|j|j|jd�}||d|j|j|jd�}| ¡ S )Nr   .)r   r   Ú
differenceÚindexÚ	tolerancer   c                   sV   ˆr| |  ¡ › d|› �7 } n| d|› d|› d|› �7 } ˆ sJ| d|› d�7 } | d7 } | S )Nz difference: z	Greatest z
 at index z (up to z	 allowed)Ú
)Útitle)r   r   rq   rr   rs   ©ZequalityZscalar_comparisonr   r   Úappend_differenceY  s    z-_make_mismatch_msg.<locals>.append_differenceZScalarszTensor-likesz	 are not ÚequalÚclosez!

zMismatched elements: z / z (z.1%z)
Úabsolute)r   rq   rr   rs   Úrelative)ÚsizerP   ÚSizer5   r6   r$   Úfloatr   rn   Úcallablere   rd   rf   rg   rh   ri   Ústrip)r'   r(   rp   r8   rw   Zdefault_identifierr   r   rv   r   r>   O  s<    &
ÿÿûûr>   )r-   r   c                 C   s"   | j rtjS | jrtjS tjS dS )zÌSelects the comparison dtype based on the input dtype.

    Returns:
        Highest precision dtype of the same dtype category as the input. :class:`torch.bool` is treated as integral
        dtype.
    N)Z
is_complexrP   Ú
complex128Zis_floating_pointÚfloat64Úint64)r-   r   r   r   Ú_get_comparison_dtypeƒ  s
    r„   )r'   r(   r5   r6   Ú	equal_nanr   r   c          	      C   s~   t | jƒ}|  |¡} | |¡}tj| ||||d� }t |¡sBdS t| ||||d�}|du r`t}t|ƒrt|| ||ƒ}t	t
|ƒS )aŠ  Checks if the values of two tensors are close up to a desired tolerance.

    Args:
        actual (Tensor): Actual tensor.
        expected (Tensor): Expected tensor.
        rtol (float): Relative tolerance.
        atol (float): Absolute tolerance.
        equal_nan (bool): If ``True``, two ``NaN`` values will be considered equal.
        msg (Optional[Union[str, Callable[[Tensor, Tensor, Diagnostics], str]]]): Optional error message. Can be passed
            as callable in which case it will be called with the inputs and the result of :func:`_trace_mismatches`.

    Returns:
        (Optional[AssertionError]): If check did not pass.
    )r5   r6   r…   Nr4   )r„   r-   ra   rP   ÚiscloseÚanyro   r>   r   r   r:   )	r'   r(   r5   r6   r…   r   r-   rc   rp   r   r   r   Ú_check_values_close’  s    



rˆ   F)r5   r6   r…   rV   rW   rX   rY   )r'   r(   r5   r6   r…   rV   rW   rX   rY   r   r   c                C   sŠ   |du s|du rt | |ƒ\}}t| |||||d�}
|
r:|
S t| |ƒ\} }|du sX|du rjt | jd¡\}}t| |||||	d�}
|
r†|
S dS )a	  Checks that the values of :attr:`actual` and :attr:`expected` are close.

    If :attr:`actual` and :attr:`expected` are real-valued and finite, they are considered close if

    .. code::

        torch.abs(actual - expected) <= (atol + rtol * expected)

    and they have the same device (if :attr:`check_device` is ``True``), same dtype (if :attr:`check_dtype` is
    ``True``), and the same stride (if :attr:`check_stride` is ``True``). Non-finite values (``-inf`` and ``inf``) are
    only considered close if and only if they are equal. ``NaN``'s are only considered equal to each other if
    :attr:`equal_nan` is ``True``.

    For a description of the parameters see :func:`assert_close`.

    Returns:
        Optional[_TestingErrorMeta]: If checks did not pass.
    NrU   r)   )r5   r6   r…   r   )r/   r_   rb   r+   r,   r-   rˆ   )r'   r(   r5   r6   r…   rV   rW   rX   rY   r   r@   r   r   r   Ú_check_tensors_close»  s&    úr‰   c                   @   s   e Zd ZU eed< eed< dS )Ú_TensorPairr'   r(   N)r   r    r!   r   r#   r   r   r   r   rŠ   ó  s   
rŠ   z2The failure occurred at index {} of the sequences.z2The failure occurred for key '{}' of the mappings.)Úpairr2   r   c                 K   sº   t | tƒrPt| ƒD ]8\}}t|fi |¤Ž}|r|jdt |¡› �d�  S qdS t | tƒr |  ¡ D ]8\}}t|fi |¤Ž}|rb|jdt	 |¡› �d�  S qbdS t
| j| jfi |¤ŽS dS )až  Checks input pairs.

    :class:`list`'s or :class:`dict`'s are checked elementwise. Checking is performed recursively and thus nested
    containers are supported.

    Args:
        pair (Union[_TensorPair, List, Dict]): Input pair.
        **kwargs (Any): Keyword arguments passed to :func:`__check_tensors_close`.

    Returns:
        (Optional[_TestingErrorMeta]): Return value of :attr:`check_tensors`.
    ú

©r   N)Ú
isinstanceÚlistÚ	enumerateÚ_check_pair_closer   Ú_SEQUENCE_MSG_FMTSTRr\   r;   ÚitemsÚ_MAPPING_MSG_FMTSTRr‰   r'   r(   )r‹   r2   ÚidxZ	pair_itemr@   Úkeyr   r   r   r‘   ü  s    

r‘   )Útensor_or_scalar_liker   c                 C   sl   t | tƒr| }n@zt | ¡}W n0 tyN   ttdt| ƒ› d�ƒ}|df Y S 0 t|ƒ}|rd|dfS d|fS )a  Converts a tensor-or-scalar-like to a :class:`~torch.Tensor`.
    Args:
        tensor_or_scalar_like (Any): Tensor-or-scalar-like.
    Returns:

        (Tuple[Optional[_TestingErrorMeta], Optional[Tensor]]): The two elements are orthogonal, i.e. if the first is
            ``None`` the second will be valid and vice versa. Returns :class:`_TestingErrorMeta` if no tensor can be
            constructed from :attr:`actual` or :attr:`expected`. Additionally, returns any error meta from
            :func:`_check_supported_tensor`.
    z'No tensor can be constructed from type Ú.N)	rŽ   r   rP   Z	as_tensorr"   r   rS   r   rT   )r—   Ztensorr@   r   r   r   Ú
_to_tensor  s    
ÿr™   )r'   r(   Úallow_subclassesr   c                C   sŽ   t | tjƒrt |tjƒrd S dt| ƒ› dt|ƒ› d�}t | t|ƒƒpPt |t| ƒƒ}|sftt| d¡ƒS |szt| ƒt|ƒu r~d S tt| d¡ƒS )Nz'Except for Python scalars, {}, but got z and z	 instead.z'input types need to be directly relatedz3type equality is required if allow_subclasses=False)rŽ   ÚnumbersÚNumberr   r   r:   r\   )r'   r(   rš   r^   Zdirectly_relatedr   r   r   Ú_check_types=  s    r�   c                C   sX   t | ||d�}|r|dfS t| ƒ\}} |r2|dfS t|ƒ\}}|rJ|dfS dt| |ƒfS )aû  Converts a tensor-or-scalar-like pair to a :class:`_TensorPair`.

    Args:
        actual (Any): Actual tensor-or-scalar-like.
        expected (Any): Expected tensor-or-scalar-like.
        allow_subclasses (bool): If ``True`` (default) and except for Python scalars, inputs of directly related types
            are allowed. Otherwise type equality is required.

    Returns:
        (Optional[_TestingErrorMeta], Optional[_TensorPair]): The two elements are orthogonal, i.e. if the first is
            ``None`` the second will not and vice versa. Returns :class:`_TestingErrorMeta` if :attr:`actual` and
            :attr:`expected` are not scalars and do not have the same type. Additionally, returns any error meta from
            :func:`_to_tensor`.
    ©rš   N)r�   r™   rŠ   )r'   r(   rš   r@   r   r   r   Ú_to_tensor_pairO  s    rŸ   c                C   s¾  t | tjjƒrÌt | tƒsÌt |tjjƒrÌt |tƒsÌt| ƒ}t|ƒ}||krfttd|› d|› �ƒ}|dfS g }t|ƒD ]P}t	| | || |d�\}}|r¸|j
dt |¡› �d�}|df  S | |¡ qrd|fS t | tjjƒ�r¬t |tjjƒ�r¬t|  ¡ ƒ}	t| ¡ ƒ}
|	|
k�rD|
|	 }|	|
 }ttdt|ƒ› dt|ƒ› �ƒ}|dfS i }t|	ƒD ]R}t	| | || |d�\}}|�r˜|j
dt |¡› �d�}|df  S |||< �qPd|fS t| ||d�S dS )	aW  Parses the positional inputs by constructing :class:`_TensorPair`'s from corresponding tensor-or-scalar-likes.


    :class:`~collections.abc.Sequence`'s or :class:`~collections.abc.Mapping`'s are parsed elementwise. Parsing is
    performed recursively and thus nested containers are supported. The hierarchy of the containers is preserved, but
    sequences are returned as :class:`list` and mappings as :class:`dict`.

    Args:
        actual (Any): Actual input.
        expected (Any): Expected input.
        allow_subclasses (bool): If ``True`` (default) and except for Python scalars, inputs of directly related types
            are allowed. Otherwise type equality is required.

    Returns:
        (Tuple[Optional[_TestingErrorMeta], Optional[Union[_TensorPair, List, Dict]]]): The two elements are
            orthogonal, i.e. if the first is ``None`` the second will be valid and vice versa. Returns
            :class:`_TestingErrorMeta` if the length of two sequences or the keys of two mappings do not match.
            Additionally, returns any error meta from :func:`_to_tensor_pair`.

    z&The length of the sequences mismatch: r3   Nrž   rŒ   r�   zKThe keys of the mappings do not match:
Missing keys in the actual mapping: z(
Additional keys in the actual mapping: )rŽ   ÚcollectionsÚabcÚSequencer$   Úlenr   r:   ÚrangeÚ_parse_inputsr   r’   r\   ÚappendÚMappingÚsetÚkeysÚsortedr”   rŸ   )r'   r(   rš   Z
actual_lenÚexpected_lenr@   Z	pair_listr•   r‹   Zactual_keysZexpected_keysZmissing_keysZadditional_keysZ	pair_dictr–   r   r   r   r¥   o  s^    ÿþýüÿ 
ÿþþr¥   )	rš   r5   r6   r…   rV   rW   rX   rY   r   )r'   r(   rš   r5   r6   r…   rV   rW   rX   rY   r   r   c       	         C   sŽ   d}|du |du A r0t d|du r$dnd› d�ƒ‚t| ||d�\}}|rP| ¡ ‚ntttttf |ƒ}t||||||||	|
d�	}|rŠ| ¡ ‚dS )	aZ4  Asserts that :attr:`actual` and :attr:`expected` are close.

    If :attr:`actual` and :attr:`expected` are strided, non-quantized, real-valued, and finite, they are considered
    close if

    .. math::

        \lvert \text{actual} - \text{expected} \rvert \le \texttt{atol} + \texttt{rtol} \cdot \lvert \text{expected} \rvert

    and they have the same :attr:`~torch.Tensor.device` (if :attr:`check_device` is ``True``), same ``dtype`` (if
    :attr:`check_dtype` is ``True``), and the same stride (if :attr:`check_stride` is ``True``). Non-finite values
    (``-inf`` and ``inf``) are only considered close if and only if they are equal. ``NaN``'s are only considered equal
    to each other if :attr:`equal_nan` is ``True``.

    If :attr:`actual` and :attr:`expected` are sparse (either having COO or CSR layout), their strided members are
    checked individually. Indices, namely ``indices`` for COO or ``crow_indices``  and ``col_indices`` for CSR layout,
    are always checked for equality whereas the values are checked for closeness according to the definition above.
    Sparse COO tensors are only considered close if both are either coalesced or uncoalesced (if
    :attr:`check_is_coalesced` is ``True``).

    If :attr:`actual` and :attr:`expected` are quantized, they are considered close if they have the same
    :meth:`~torch.Tensor.qscheme` and the result of :meth:`~torch.Tensor.dequantize` is close according to the
    definition above.

    :attr:`actual` and :attr:`expected` can be :class:`~torch.Tensor`'s or any tensor-or-scalar-likes from which
    :class:`torch.Tensor`'s can be constructed with :func:`torch.as_tensor`. Except for Python scalars the input types
    have to be directly related. In addition, :attr:`actual` and :attr:`expected` can be
    :class:`~collections.abc.Sequence`'s or :class:`~collections.abc.Mapping`'s in which case they are considered close
    if their structure matches and all their elements are considered close according to the above definition.

    .. note::

        Python scalars are an exception to the type relation requirement, because their :func:`type`, i.e.
        :class:`int`, :class:`float`, and :class:`complex`, is equivalent to the ``dtype`` of a tensor-like. Thus,
        Python scalars of different types can be checked, but require :attr:`check_dtype` to be set to ``False``.

    Args:
        actual (Any): Actual input.
        expected (Any): Expected input.
        allow_subclasses (bool): If ``True`` (default) and except for Python scalars, inputs of directly related types
            are allowed. Otherwise type equality is required.
        rtol (Optional[float]): Relative tolerance. If specified :attr:`atol` must also be specified. If omitted,
            default values based on the :attr:`~torch.Tensor.dtype` are selected with the below table.
        atol (Optional[float]): Absolute tolerance. If specified :attr:`rtol` must also be specified. If omitted,
            default values based on the :attr:`~torch.Tensor.dtype` are selected with the below table.
        equal_nan (Union[bool, str]): If ``True``, two ``NaN`` values will be considered equal.
        check_device (bool): If ``True`` (default), asserts that corresponding tensors are on the same
            :attr:`~torch.Tensor.device`. If this check is disabled, tensors on different
            :attr:`~torch.Tensor.device`'s are moved to the CPU before being compared.
        check_dtype (bool): If ``True`` (default), asserts that corresponding tensors have the same ``dtype``. If this
            check is disabled, tensors with different ``dtype``'s are promoted  to a common ``dtype`` (according to
            :func:`torch.promote_types`) before being compared.
        check_stride (bool): If ``True`` and corresponding tensors are strided, asserts that they have the same stride.
        check_is_coalesced (bool): If ``True`` (default) and corresponding tensors are sparse COO, checks that both
            :attr:`actual` and :attr:`expected` are either coalesced or uncoalesced. If this check is disabled,
            tensors are :meth:`~torch.Tensor.coalesce`'ed before being compared.
        msg (Optional[Union[str, Callable[[Tensor, Tensor, Diagnostics], str]]]): Optional error message to use if the
            values of corresponding tensors mismatch. Can be passed as callable in which case it will be called with
            the mismatching tensors and a namespace of diagnostics about the mismatches. See below for details.

    Raises:
        ValueError: If no :class:`torch.Tensor` can be constructed from an input.
        ValueError: If only :attr:`rtol` or :attr:`atol` is specified.
        AssertionError: If corresponding inputs are not Python scalars and are not directly related.
        AssertionError: If :attr:`allow_subclasses` is ``False``, but corresponding inputs are not Python scalars and
            have different types.
        AssertionError: If the inputs are :class:`~collections.abc.Sequence`'s, but their length does not match.
        AssertionError: If the inputs are :class:`~collections.abc.Mapping`'s, but their set of keys do not match.
        AssertionError: If corresponding tensors do not have the same :attr:`~torch.Tensor.shape`.
        AssertionError: If corresponding tensors do not have the same :attr:`~torch.Tensor.layout`.
        AssertionError: If corresponding tensors are quantized, but have different :meth:`~torch.Tensor.qscheme`'s.
        AssertionError: If :attr:`check_device` is ``True``, but corresponding tensors are not on the same
            :attr:`~torch.Tensor.device`.
        AssertionError: If :attr:`check_dtype` is ``True``, but corresponding tensors do not have the same ``dtype``.
        AssertionError: If :attr:`check_stride` is ``True``, but corresponding strided tensors do not have the same
            stride.
        AssertionError: If :attr:`check_is_coalesced`  is ``True``, but corresponding sparse COO tensors are not both
            either coalesced or uncoalesced.
        AssertionError: If the values of corresponding tensors are not close according to the definition above.

    The following table displays the default ``rtol`` and ``atol`` for different ``dtype``'s. In case of mismatching
    ``dtype``'s, the maximum of both tolerances is used.

    +---------------------------+------------+----------+
    | ``dtype``                 | ``rtol``   | ``atol`` |
    +===========================+============+==========+
    | :attr:`~torch.float16`    | ``1e-3``   | ``1e-5`` |
    +---------------------------+------------+----------+
    | :attr:`~torch.bfloat16`   | ``1.6e-2`` | ``1e-5`` |
    +---------------------------+------------+----------+
    | :attr:`~torch.float32`    | ``1.3e-6`` | ``1e-5`` |
    +---------------------------+------------+----------+
    | :attr:`~torch.float64`    | ``1e-7``   | ``1e-7`` |
    +---------------------------+------------+----------+
    | :attr:`~torch.complex32`  | ``1e-3``   | ``1e-5`` |
    +---------------------------+------------+----------+
    | :attr:`~torch.complex64`  | ``1.3e-6`` | ``1e-5`` |
    +---------------------------+------------+----------+
    | :attr:`~torch.complex128` | ``1e-7``   | ``1e-7`` |
    +---------------------------+------------+----------+
    | other                     | ``0.0``    | ``0.0``  |
    +---------------------------+------------+----------+

    The namespace of diagnostics that will be passed to :attr:`msg` if its a callable has the following attributes:

    - ``number_of_elements`` (int): Number of elements in each tensor being compared.
    - ``total_mismatches`` (int): Total number of mismatches.
    - ``max_abs_diff`` (Union[int, float]): Greatest absolute difference of the inputs.
    - ``max_abs_diff_idx`` (Union[int, Tuple[int, ...]]): Index of greatest absolute difference.
    - ``atol`` (float): Allowed absolute tolerance.
    - ``max_rel_diff`` (Union[int, float]): Greatest relative difference of the inputs.
    - ``max_rel_diff_idx`` (Union[int, Tuple[int, ...]]): Index of greatest relative difference.
    - ``rtol`` (float): Allowed relative tolerance.

    For ``max_abs_diff`` and ``max_rel_diff`` the type depends on the :attr:`~torch.Tensor.dtype` of the inputs.

    .. note::

        :func:`~torch.testing.assert_close` is highly configurable with strict default settings. Users are encouraged
        to :func:`~functools.partial` it to fit their use case. For example, if an equality check is needed, one might
        define an ``assert_equal`` that uses zero tolrances for every ``dtype`` by default:

        >>> import functools
        >>> assert_equal = functools.partial(torch.testing.assert_close, rtol=0, atol=0)
        >>> assert_equal(1e-9, 1e-10)
        Traceback (most recent call last):
        ...
        AssertionError: Scalars are not equal!
        <BLANKLINE>
        Absolute difference: 8.999999703829253e-10
        Relative difference: 8.999999583666371

    Examples:
        >>> # tensor to tensor comparison
        >>> expected = torch.tensor([1e0, 1e-1, 1e-2])
        >>> actual = torch.acos(torch.cos(expected))
        >>> torch.testing.assert_close(actual, expected)

        >>> # scalar to scalar comparison
        >>> import math
        >>> expected = math.sqrt(2.0)
        >>> actual = 2.0 / math.sqrt(2.0)
        >>> torch.testing.assert_close(actual, expected)

        >>> # numpy array to numpy array comparison
        >>> import numpy as np
        >>> expected = np.array([1e0, 1e-1, 1e-2])
        >>> actual = np.arccos(np.cos(expected))
        >>> torch.testing.assert_close(actual, expected)

        >>> # sequence to sequence comparison
        >>> import numpy as np
        >>> # The types of the sequences do not have to match. They only have to have the same
        >>> # length and their elements have to match.
        >>> expected = [torch.tensor([1.0]), 2.0, np.array(3.0)]
        >>> actual = tuple(expected)
        >>> torch.testing.assert_close(actual, expected)

        >>> # mapping to mapping comparison
        >>> from collections import OrderedDict
        >>> import numpy as np
        >>> foo = torch.tensor(1.0)
        >>> bar = 2.0
        >>> baz = np.array(3.0)
        >>> # The types and a possible ordering of mappings do not have to match. They only
        >>> # have to have the same set of keys and their elements have to match.
        >>> expected = OrderedDict([("foo", foo), ("bar", bar), ("baz", baz)])
        >>> actual = {"baz": baz, "bar": bar, "foo": foo}
        >>> torch.testing.assert_close(actual, expected)

        >>> expected = torch.tensor([1.0, 2.0, 3.0])
        >>> actual = expected.clone()
        >>> # By default, directly related instances can be compared
        >>> torch.testing.assert_close(torch.nn.Parameter(actual), expected)
        >>> # This check can be made more strict with allow_subclasses=False
        >>> torch.testing.assert_close(
        ...     torch.nn.Parameter(actual), expected, allow_subclasses=False
        ... )
        Traceback (most recent call last):
        ...
        AssertionError: Except for Python scalars, type equality is required if
        allow_subclasses=False, but got <class 'torch.nn.parameter.Parameter'> and
        <class 'torch.Tensor'> instead.
        >>> # If the inputs are not directly related, they are never considered close
        >>> torch.testing.assert_close(actual.numpy(), expected)
        Traceback (most recent call last):
        ...
        AssertionError: Except for Python scalars, input types need to be directly
        related, but got <class 'numpy.ndarray'> and <class 'torch.Tensor'> instead.
        >>> # Exceptions to these rules are Python scalars. They can be checked regardless of
        >>> # their type if check_dtype=False.
        >>> torch.testing.assert_close(1.0, 1, check_dtype=False)

        >>> # NaN != NaN by default.
        >>> expected = torch.tensor(float("Nan"))
        >>> actual = expected.clone()
        >>> torch.testing.assert_close(actual, expected)
        Traceback (most recent call last):
        ...
        AssertionError: Scalars are not close!
        <BLANKLINE>
        Absolute difference: nan (up to 1e-05 allowed)
        Relative difference: nan (up to 1.3e-06 allowed)
        >>> torch.testing.assert_close(actual, expected, equal_nan=True)

        >>> expected = torch.tensor([1.0, 2.0, 3.0])
        >>> actual = torch.tensor([1.0, 4.0, 5.0])
        >>> # The default mismatch message can be overwritten.
        >>> torch.testing.assert_close(actual, expected, msg="Argh, the tensors are not close!")
        Traceback (most recent call last):
        ...
        AssertionError: Argh, the tensors are not close!
        >>> # The error message can also created at runtime by passing a callable.
        >>> def custom_msg(actual, expected, diagnostics):
        ...     ratio = diagnostics.total_mismatches / diagnostics.number_of_elements
        ...     return (
        ...         f"Argh, we found {diagnostics.total_mismatches} mismatches! "
        ...         f"That is {ratio:.1%}!"
        ...     )
        >>> torch.testing.assert_close(actual, expected, msg=custom_msg)
        Traceback (most recent call last):
        ...
        AssertionError: Argh, we found 2 mismatches! That is 66.7%!
    TNzGBoth 'rtol' and 'atol' must be either specified or omitted, but got no r5   r6   r˜   rž   )r5   r6   r…   rV   rW   rX   rY   r   )	rS   r¥   r   r   r
   rŠ   r   r   r‘   )r'   r(   rš   r5   r6   r…   rV   rW   rX   rY   r   Z__tracebackhide__r@   r‹   r   r   r   r   À  s2     pÿÿ
÷)9Úcollections.abcr    r<   r›   Útypingr   r   r   r   r   r   r   r	   r
   r   Útypesr   rE   rP   r   Z_corer   Ú__all__r   Úfloat16Zbfloat16Úfloat32r‚   Z	complex32Z	complex64r�   r+   r~   r/   rG   rI   rM   rT   Úboolr_   rb   ro   r$   r>   r-   r„   rˆ   r‰   rŠ   r’   r”   r‘   r™   r�   rŸ   r¥   r   r   r   r   r   Ú<module>   sò   0ùþ7þ8þùø<9ûú4ø*öô8ý" þ!þUôó