
    Ǆg                     `   d dl Z 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mZ d dlmZ d dlZ	 d dlZdZ G d de      Zej4                  dej6                  d	ej8                  d
ej:                  dej<                  dej>                  d
ej@                  diZ!e!jE                  e#jI                  ejJ                  ejL                  ejN                  ejP                  ejR                  fe!ej8                                  dddeejT                  ejV                  f   dee	ejV                  ee,e,f   f      dee,e,f   fdZ-dddeejT                  ejV                  f   dee,   dee,   deedf   dee,e,f   f
dZ.dddddde/deee/ee/ge/f   f      dee/   de,deee0ee0df   f      de,de,deee0ee0df   f      de,de/fd Z1dd!d"ee2e0e,e3f   d#ee2e0e,e3f   de,de,deee/ee/ge/f   f      de/fd$Z4dd!d"ejT                  d#ejT                  d%ejT                  de,de,deee/ee/ge/f   f      fd&Z5 G d' d(e      Z6 G d) d*e jn                        Z8 G d+ d,e8      Z9 G d- d.e8      Z: G d/ d0e8      Z; G d1 d2e8      Z< G d3 d4e8      Z=ej                   j                  fej                   j|                  fdd5d"ed#ed6eee8      d7eedf   d8eedf   deedf   d9ede
e8   fd:Z?e9fej                   j                  fej                   j|                  fd;d"ed#ed6eee8      d7eedf   d8eedf   d9ede
e   fd<Z@dddddddddd=	d"ed#ed>e2dee,   dee,   d?e2d@e2dAe2dBe2dCe2dDeee/ee/ge/f   f      fdEZA edFeBG      	 	 	 	 dId"ed#edee,   dee,   d?e2dDe/ddfdH       ZCy# e$ r dZdZY pw xY w)J    N)AnyCallable
CollectionDictListNoReturnOptionalSequenceTupleTypeUnion)
deprecatedTFc            	       z     e Zd ZdZdddee   dedeedf   dd	f fd
Z		 dde
eeeegef   f      defdZ xZS )	ErrorMetazBInternal testing exception that makes that carries error metadata. idtypemsgr   .returnNc                N    t         |   d       || _        || _        || _        y )NzIf you are a user and see this message during normal operation please file an issue at https://github.com/pytorch/pytorch/issues. If you are a developer and working on the comparison functions, please `raise ErrorMeta.to_error()` for user facing errors.)super__init__r   r   r   )selfr   r   r   	__class__s       a/home/mcse/projects/flask_80/flask-venv/lib/python3.12/site-packages/torch/testing/_comparison.pyr   zErrorMeta.__init__$   s.     	&	
 	    c                     t        |t              sU| j                  }| j                  r(|ddj	                  d | j                  D               z  }t        |      r ||      n|}| j                  |      S )Nz 

The failure occurred for item  c              3   4   K   | ]  }t        |g        y wNstr.0items     r   	<genexpr>z%ErrorMeta.to_error.<locals>.<genexpr>7   s     Mn^bcSWRXkMn   )
isinstancer#   r   r   joincallabler   )r   r   generated_msgs      r   to_errorzErrorMeta.to_error1   sg     #s# HHMww#EbggMnfjfmfmMnFnEo!pp(0#m$=Cyy~r   r!   )__name__
__module____qualname____doc__r   	Exceptionr#   r   r   r   r	   r   r   r-   __classcell__r   s   @r   r   r   !   st    L IKO*-6;CHo	 AE
E#xs
';";<=
	
r   r   )MbP?h㈵>)gMb?r6   )gkNuϵ>r6   )Hz>r7   dtype_precisionsinputsr9   r   c           	         g }|D ]{  }t        |t        j                        r|j                  |j                         9t        |t        j                        r|j                  |       et        dt        |       d       | xs t        } t        |D cg c]  }| j                  |d       c} \  }}t        |      t        |      fS c c}w )a  Returns the default absolute and relative testing tolerances for a set of inputs based on the dtype.

    See :func:`assert_close` for a table of the default tolerance for each dtype.

    Returns:
        (Tuple[float, float]): Loosest tolerances of all input dtypes.
    z2Expected a torch.Tensor or a torch.dtype, but got z	 instead.)        r<   )r)   torchTensorappenddtype	TypeErrorr   _DTYPE_PRECISIONSzipgetmax)r9   r:   dtypesinputr@   rtolsatolss          r   default_tolerancesrJ   T   s     F eU\\*MM%++&u{{+MM% DT%[MQZ[  (<+<fUU)--eZ@UVLE5u:s5z!! Vs   Cr   r   rtolatolr   .c                 h    | du |du z  rt        t        d| dnd d|      | || |fS t        | S )a  Gets absolute and relative to be used for numeric comparisons.

    If both ``rtol`` and ``atol`` are specified, this is a no-op. If both are not specified, the return value of
    :func:`default_tolerances` is used.

    Raises:
        ErrorMeta: With :class:`ValueError`, if only ``rtol`` or ``atol`` is specified.

    Returns:
        (Tuple[float, float]): Valid absolute and relative tolerances.
    NzGBoth 'rtol' and 'atol' must be either specified or omitted, but got no rK   rL   .r   )r   
ValueErrorrJ   )rK   rL   r   r:   s       r   get_tolerancesrP   n   sd    " 	& $(L&f=Q@	
 	
 
	d.Tz!6**r   )
identifierextraabs_diff_idxrel_diff_idxdefault_identifierrQ   rR   abs_diffrS   rel_diffrT   c        	         r   |dk(  xr |dk(  dt         dt        dt        t        t        t
        t        df   f      dt        dt         f
fd}	|| }nt        |      r ||       }| d	rd
nd d}
|r|
|j                          dz  }
|
 |	d|||      z  }
|
 |	d|||      z  }
|
j                         S )ag  Makes a mismatch error message for numeric values.

    Args:
        default_identifier (str): Default description of the compared values, e.g. "Tensor-likes".
        identifier (Optional[Union[str, Callable[[str], str]]]): Optional identifier that overrides
            ``default_identifier``. Can be passed as callable in which case it will be called with
            ``default_identifier`` to create the description at runtime.
        extra (Optional[str]): Extra information to be placed after the message header and the mismatch statistics.
        abs_diff (float): Absolute difference.
        abs_diff_idx (Optional[Union[int, Tuple[int, ...]]]): Optional index of the absolute difference.
        atol (float): Allowed absolute tolerance. Will only be added to mismatch statistics if it or ``rtol`` are
            ``> 0``.
        rel_diff (float): Relative difference.
        rel_diff_idx (Optional[Union[int, Tuple[int, ...]]]): Optional index of the relative difference.
        rtol (float): Allowed relative tolerance. Will only be added to mismatch statistics if it or ``atol`` are
            ``> 0``.
    r   r   diffidx.tolr   c                 j    || j                          d| }nd|  d| d| }s	|d| dz  }|dz   S )Nz difference: z	Greatest z
 at index z (up to z	 allowed)
)title)r   rY   rZ   r[   r   equalitys        r   make_diff_msgz)_make_mismatch_msg.<locals>.make_diff_msg   sX     ;ZZ\N-v6CdV=jFCXcU),,CTzr   z	 are not equalclosez!

r]   absolute)r   rY   rZ   r[   relative)r#   floatr	   r   intr   r+   strip)rU   rQ   rR   rV   rS   rL   rW   rT   rK   r`   r   r_   s              @r   _make_mismatch_msgrh      s    : qy&TQYH  eCsCx012	
  
 '
	*	 23
L	X'7!C5
IC%++-##=jx\tTTC=jx\tTTC99;r   rQ   actualexpectedc          	          t        | |z
        }|dk(  rt        d      n|t        |      z  }t        d|d| d|  d||||      S )a"  Makes a mismatch error message for scalars.

    Args:
        actual (Union[bool, int, float, complex]): Actual scalar.
        expected (Union[bool, int, float, complex]): Expected scalar.
        rtol (float): Relative tolerance.
        atol (float): Absolute tolerance.
        identifier (Optional[Union[str, Callable[[str], str]]]): Optional description for the scalars. Can be passed
            as callable in which case it will be called by the default value to create the description at runtime.
            Defaults to "Scalars".
    r   infScalarsz	Expected z	 but got rN   )rU   rQ   rR   rV   rL   rW   rK   )absre   rh   )rj   rk   rK   rL   rQ   rV   rW   s          r   make_scalar_mismatch_msgrp      s^    & 6H$%H'1}uU|(S]2JH$(9VHA6 r   matchesc                d   dt         dt        t         df   ffd}j                         }|t        t        j                              z
  }d| d| d||z  dd	}	| j                         }
|j                         }j                         }| j                  j                  sT| j                  j                  s>|
j                  t        j                        }
|j                  t        j                        }t        j                  |
|z
        }d
||<   t        j                  |d
      \  }}|t        j                  |      z  }d
||<   t        j                  |d
      \  }}t        d||	|j                          |t        |            ||j                          |t        |            |	      S )a  Makes a mismatch error message for tensors.

    Args:
        actual (torch.Tensor): Actual tensor.
        expected (torch.Tensor): Expected tensor.
        matches (torch.Tensor): Boolean mask of the same shape as ``actual`` and ``expected`` that indicates the
            location of matches.
        rtol (float): Relative tolerance.
        atol (float): Absolute tolerance.
        identifier (Optional[Union[str, Callable[[str], str]]]): Optional description for the tensors. Can be passed
            as callable in which case it will be called by the default value to create the description at runtime.
            Defaults to "Tensor-likes".
    
flat_indexr   .c                     j                   syg }j                   d d d   D ]$  }t        | |      \  }}|} |j                  |       & t        |d d d         S )Nr   )shapedivmodr?   tuple)rs   inverse_indexsizedivmodrq   s        r   unravel_flat_indexz4make_tensor_mismatch_msg.<locals>.unravel_flat_index  sg    }}MM$B$' 	&Dj$/HCJ  %	&
 ]4R4())r   zMismatched elements: z / z (z.1%)r   zTensor-likes)	rU   rQ   rR   rV   rS   rL   rW   rT   rK   )rf   r   numelr=   sumflattenr@   is_floating_point
is_complextoint64ro   rE   rh   r&   )rj   rk   rq   rK   rL   rQ   r}   number_of_elementstotal_mismatchesrR   actual_flatexpected_flatmatches_flatrV   max_abs_diffmax_abs_diff_flat_idxrW   max_rel_diffmax_rel_diff_flat_idxs     `                r   make_tensor_mismatch_msgr      s   .
*s 
*uS#X 
* !)C		'0B,CC
 015G4H I11#6a	9 

 .."K$$&M??$L<<))&,,2I2I "nnU[[1%((5yy}45HH\*/))Ha*@'L'%))M22HH\*/))Ha*@'L')""$',A(BC""$',A(BC
 
r   c                       e Zd ZdZy)UnsupportedInputszhException to be raised during the construction of a :class:`Pair` in case it doesn't support the inputs.N)r.   r/   r0   r1   r   r   r   r   r   6  s    rr   r   c                      e Zd ZdZdddededeedf   ded	d
f
dZed	efd       Z	edede
eeedf   f   fd       Zdddee   dedeedf   d	efdZej"                  dd       Zd	ee
eeeef   f      fdZd	efdZy
)Paira  ABC for all comparison pairs to be used in conjunction with :func:`assert_equal`.

    Each subclass needs to overwrite :meth:`Pair.compare` that performs the actual comparison.

    Each pair receives **all** options, so select the ones applicable for the subclass and forward the rest to the
    super class. Raising an :class:`UnsupportedInputs` during constructions indicates that the pair is not able to
    handle the inputs and the next pair type will be tried.

    All other errors should be raised as :class:`ErrorMeta`. After the instantiation, :meth:`Pair._make_error_meta` can
    be used to automatically handle overwriting the message with a user supplied one and id handling.
    r   r   rj   rk   r   .unknown_parametersr   Nc                <    || _         || _        || _        || _        y r!   )rj   rk   r   _unknown_parameters)r   rj   rk   r   r   s        r   r   zPair.__init__G  s!      #5 r   c                      t         r!   )r   r   r   r   _inputs_not_supportedzPair._inputs_not_supportedT  s    r   r:   clsc                 X     t         fd|D              st        j                          yy)zcChecks if all inputs are instances of a given class and raise :class:`UnsupportedInputs` otherwise.c              3   6   K   | ]  }t        |        y wr!   )r)   )r%   rG   r   s     r   r'   z0Pair._check_inputs_isinstance.<locals>.<genexpr>[  s     >e:eS)>s   N)allr   r   )r   r:   s   ` r   _check_inputs_isinstancezPair._check_inputs_isinstanceX  s$     >v>>&&( ?r   r   r   c                \    t        |||st        | d      r| j                        |      )a  Raises an :class:`ErrorMeta` from a given exception type and message and the stored id.

        .. warning::

            If you use this before the ``super().__init__(...)`` call in the constructor, you have to pass the ``id``
            explicitly.
        r   r   )r   hasattrr   )r   r   r   r   s       r   _failz
Pair._fail^  s+     cRGD$<OdggXXUWXXr   c                      y)zJCompares the inputs and raises an :class`ErrorMeta` in case they mismatch.Nr   r   s    r   comparezPair.comparej  s    r   c                     g S )al  Returns extra information that will be included in the representation.

        Should be overwritten by all subclasses that use additional options. The representation of the object will only
        be surfaced in case we encounter an unexpected error and thus should help debug the issue. Can be a sequence of
        key-value-pairs or attribute names.
        r   r   s    r   
extra_reprzPair.extra_reprn  s	     	r   c           	      v   t        |       j                   d}d}d| j                  fd| j                  fd| j                  fg| j                         D cg c]"  }t        |t              r|t        | |      fn|$ c}D cg c]  \  }}d| d|d }}}d	j                  |g||      S c c}w c c}}w )
N(r~   r   rj   rk   z    =,r]   )
r   r.   r   rj   rk   r   r)   r#   getattrr*   )r   headtailrR   namevaluebodys          r   __repr__zPair.__repr__w  s    t*%%&a( tww4;;'T]]+  "&!2 6@s5KUGD%01QVV	 
e 4&%!$
 
 yy$---..
s   'B0B5r   N)r.   r/   r0   r1   r   r   r   staticmethodr   r   r   r   r   r2   r#   r   abcabstractmethodr   r
   r   r   r   r   r   r   r   :  s!   
" !66 6
 #s(O6 "6 
6  8     )# )E$dCi@P:P4Q ) ) IK
YO
Y*-
Y6;CHo
Y	
Y 	Y YHU3c3h+?%@A /# /r   r   c                       e Zd ZdZddZy)
ObjectPairzPair for any type of inputs that will be compared with the `==` operator.

    .. note::

        Since this will instantiate for any kind of inputs, it should only be used as fallback after all other pairs
        couldn't handle the inputs.

    Nc           
      2   	 | j                   | j                  k(  }|s0| j                  t        | j                    d| j                          y y # t        $ r?}t        t        | j                    d| j                   d| d| j
                        |d }~ww xY w)Nz == z failed with:
rN   r    != )rj   rk   r2   r   rO   r   r   AssertionError)r   ra   errors      r   r   zObjectPair.compare  s    	KK4==0E JJ~$++d4==/'JK   	;;-tDMM?/%J77 		s   A 	B:BBr   )r.   r/   r0   r1   r   r   r   r   r   r     s    Lr   r   c                   <     e Zd ZdZdedededdf fdZd	dZ xZS )
NonePairzPair for ``None`` inputs.rj   rk   other_parametersr   Nc                 P    ||| j                          t        |   ||fi | y r!   )r   r   r   )r   rj   rk   r   r   s       r   r   zNonePair.__init__  s.    ("2&&(>-=>r   c                     | j                   | j                  1| j                  t        d| j                    d| j                          y y )NzNone mismatch:  is not rj   rk   r   r   r   s    r   r   zNonePair.compare  s@    #(=JJ/$++ht}}o V )>r   r   )r.   r/   r0   r1   r   r   r   r3   r4   s   @r   r   r     s,    #?s ?c ?s ?t ?r   r   c            
            e Zd ZdZdededeedf   deddf
 fd	Zedeedf   fd
       Z	dededeedf   dee
e
f   fdZdedeedf   de
fdZddZ xZS )BooleanPairzPair for :class:`bool` inputs.

    .. note::

        If ``numpy`` is available, also handles :class:`numpy.bool_` inputs.

    rj   rk   r   .r   r   Nc                V    | j                  |||      \  }}t        |   ||fi | y )Nr   )_process_inputsr   r   )r   rj   rk   r   r   r   s        r   r   zBooleanPair.__init__  s6      //R/H>-=>r   c                 p    t         g}t        r|j                  t        j                         t        |      S r!   )bool	HAS_NUMPYr?   npbool_rx   r   r   s     r   _supported_typeszBooleanPair._supported_types  s&    &JJrxx Szr   c                l      j                  || j                          fd||fD        \  }}||fS )Nr   c              3   D   K   | ]  }j                  |         ywr   N)_to_bool)r%   	bool_liker   r   s     r   r'   z.BooleanPair._process_inputs.<locals>.<genexpr>  s#      
09DMM)M+
    r   r   r   rj   rk   r   s   `  `r   r   zBooleanPair._process_inputs  sF     	%%fhD<Q<Q%R
>Dh=O
 xr   r   c                    t        |t              r|S t        |t        j                        r|j	                         S t        t        dt        |       d|      )NzUnknown boolean type rN   r   )r)   r   r   r   r&   r   rA   r   )r   r   r   s      r   r   zBooleanPair._to_bool  sP    i&	288,>>##24	?2C1E" r   c                     | j                   | j                  ur1| j                  t        d| j                    d| j                          y y )NzBooleans mismatch: r   r   r   s    r   r   zBooleanPair.compare  s>    ;;dmm+JJ%dkk](4==/J ,r   r   )r.   r/   r0   r1   r   r   r   propertyr   r   r   r   r   r   r3   r4   s   @r   r   r     s    	?	? 	?
 #s(O	?  	? 
	? %c	"2    %( 16sCx 	tTz	 # eCHo $ r   r   c                       e Zd ZdZeej                  eej                  e	ej                  iZ eej                               Zdddddddededeed	f   d
ee   dee   dedededdf fdZedeed	f   fd       Zdededeed	f   deeeee	f   eeee	f   f   fdZdedeed	f   deeee	f   fdZddZdee   fdZ xZS )
NumberPaira  Pair for Python number (:class:`int`, :class:`float`, and :class:`complex`) inputs.

    .. note::

        If ``numpy`` is available, also handles :class:`numpy.number` inputs.

    Kwargs:
        rtol (Optional[float]): Relative tolerance. If specified ``atol`` must also be specified. If omitted, default
            values based on the type are selected with the below table.
        atol (Optional[float]): Absolute tolerance. If specified ``rtol`` must also be specified. If omitted, default
            values based on the type are selected with the below table.
        equal_nan (bool): If ``True``, two ``NaN`` values are considered equal. Defaults to ``False``.
        check_dtype (bool): If ``True``, the type of the inputs will be checked for equality. Defaults to ``False``.

    The following table displays correspondence between Python number type and the ``torch.dtype``'s. See
    :func:`assert_close` for the corresponding tolerances.

    +------------------+-------------------------------+
    | ``type``         | corresponding ``torch.dtype`` |
    +==================+===============================+
    | :class:`int`     | :attr:`~torch.int64`          |
    +------------------+-------------------------------+
    | :class:`float`   | :attr:`~torch.float64`        |
    +------------------+-------------------------------+
    | :class:`complex` | :attr:`~torch.complex64`      |
    +------------------+-------------------------------+
    r   NF)r   rK   rL   	equal_nancheck_dtyperj   rk   r   .rK   rL   r   r   r   r   c          	          | j                  |||      \  }}t        
|   ||fd|i| t        ||fD 	cg c]  }	| j                  t        |	          c}	|||d\  | _        | _        || _        || _	        y c c}	w )Nr   r   rK   rL   r   )
r   r   r   rP   _TYPE_TO_DTYPEr   rK   rL   r   r   )r   rj   rk   r   rK   rL   r   r   r   rG   r   s             r   r   zNumberPair.__init__  s      //R/HEbE4DE-=CX<NO5d!!$u+.O	 
	49 #& Ps   A;c                     t        | j                        }t        r|j                  t        j
                         t        |      S r!   )list_NUMBER_TYPESr   r?   r   numberrx   r   s     r   r   zNumberPair._supported_types$  s/    4%%&JJryy!Szr   c                l      j                  || j                          fd||fD        \  }}||fS )Nr   c              3   D   K   | ]  }j                  |         ywr   )
_to_number)r%   number_liker   r   s     r   r'   z-NumberPair._process_inputs.<locals>.<genexpr>/  s#      
4?DOOKBO/
r   r   r   s   `  `r   r   zNumberPair._process_inputs+  sF     	%%fhD<Q<Q%R
DJHCU
 xr   r   c                    t         r*t        |t        j                        r|j	                         S t        || j
                        r|S t        t        dt        |       d|      )NzUnknown number type rN   r   )	r   r)   r   r   r&   r   r   rA   r   )r   r   r   s      r   r   zNumberPair._to_number4  s]     K;##%%T%7%781${2C1DAF2 r   c           	      .   | j                   rmt        | j                        t        | j                        urC| j	                  t
        dt        | j                         dt        | j                         d       | j                  | j                  k(  ry | j                  r?t        j                  | j                        r t        j                  | j                        ry t        | j                  | j                  z
        }| j                  | j                  t        | j                        z  z   }t        j                  |      r||k  ry | j	                  t
        t        | j                  | j                  | j                  | j                               y )NzThe (d)types do not match: r   rN   )rK   rL   )r   r   rj   rk   r   r   r   cmathisnanro   rL   rK   isfiniterp   )r   rV   	tolerances      r   r   zNumberPair.compare@  s   T[[ 1dmm9L LJJ-d4;;.?-@T$--EXDYYZ[
 ;;$--'>>ekk$++65;;t}};Ut{{T]]23II		C,> >>	>>(#I(=

$T]]	
r   c                      y)N)rK   rL   r   r   r   r   s    r   r   zNumberPair.extra_reprZ  s    
r   r   )r.   r/   r0   r1   rf   r=   r   re   float64complex
complex128r   rx   keysr   r   r   r	   r   r   r   r   r   r   r   r   r   r
   r#   r   r3   r4   s   @r   r   r     sz   : 	U[[u}}!!N
 .--/0M ! $ $!'' '
 #s(O' uo' uo' ' '  ' 
'0 %c	"2    %( 16sCx 	uS%()5eW1D+EE	F 

',S#X
	sE7"	#

4
HSM 
r   r   c                       e Zd ZdZdddddddddd	deded	eed
f   dedee   dee   dedededededef fdZ	deded	eed
f   dedee
j                  e
j                  f   f
dZdede
j                  fdZde
j                  d	eed
f   ddfdZd(dZde
j                  de
j                  ddfdZde
j                  de
j                  dee
j                  e
j                  f   fdZde
j                  de
j                  ddfdZde
j                  de
j                  dedededdfdZde
j                  de
j                  dedededdfd Zde
j                  de
j                  dedededdfd!Zddd"de
j                  de
j                  ded#eeeeegef   f      ddf
d$Zdd%de
j                  de
j                  dededed#eeeeegef   f      ddfd&Zdee   fd'Z xZS ))TensorLikePaira  Pair for :class:`torch.Tensor`-like inputs.

    Kwargs:
        allow_subclasses (bool):
        rtol (Optional[float]): Relative tolerance. If specified ``atol`` must also be specified. If omitted, default
            values based on the type are selected. See :func:assert_close: for details.
        atol (Optional[float]): Absolute tolerance. If specified ``rtol`` must also be specified. If omitted, default
            values based on the type are selected. See :func:assert_close: for details.
        equal_nan (bool): If ``True``, two ``NaN`` values are considered equal. Defaults to ``False``.
        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_layout (bool): If ``True`` (default), asserts that corresponding tensors have the same ``layout``. If this
            check is disabled, tensors with different ``layout``'s are converted to strided tensors before being
            compared.
        check_stride (bool): If ``True`` and corresponding tensors are strided, asserts that they have the same stride.
    r   TNF)	r   allow_subclassesrK   rL   r   check_devicer   check_layoutcheck_striderj   rk   r   .r   rK   rL   r   r   r   r   r   r   c       	             | j                  ||||      \  }}t        |   ||fd|i| t        ||||| j                        \  | _        | _        || _        || _        |	| _	        |
| _
        || _        y )N)r   r   r   r   )r   r   r   rP   r   rK   rL   r   r   r   r   r   )r   rj   rk   r   r   rK   rL   r   r   r   r   r   r   r   s                r   r   zTensorLikePair.__init__y  s       //H6F 0 
 	EbE4DE-H4dtww 
	49 #(&((r   r   c                0    t        |t        |            xs t        |t        |            }|s j                          |s&t        |      t        |      ur j                           fd||fD        \  }}||fD ]  } j                  ||        ||fS )Nc              3   @   K   | ]  }j                  |        y wr!   )
_to_tensor)r%   rG   r   s     r   r'   z1TensorLikePair._process_inputs.<locals>.<genexpr>  s     SuDOOE2Ss   r   )r)   r   r   _check_supported)r   rj   rk   r   r   directly_relatedtensors   `      r   r   zTensorLikePair._process_inputs  s     &fd8n= 
d6lB
  &&(DLX$F&&(S@RSx( 	1F!!&R!0	1xr   tensor_likec                     t        |t        j                        r|S 	 t        j                  |      S # t        $ r | j                          Y y w xY wr!   )r)   r=   r>   	as_tensorr2   r   )r   r   s     r   r   zTensorLikePair._to_tensor  sE    k5<<0	)??;// 	)&&(	)s   3 AAr   c                0   |j                   t        j                  t        j                  t        j                  t        j
                  t        j                  t        j                  t        j                  hvrt        t        d|j                    |      y )NzUnsupported tensor layout r   )layoutr=   stridedjagged
sparse_coo
sparse_csr
sparse_csc
sparse_bsr
sparse_bscr   rO   )r   r   r   s      r   r   zTensorLikePair._check_supported  su    ==MMLL!
 
 8HR 
r   c                     | j                   | j                  }}| j                  ||       t        d ||fD              ry | j	                  ||      \  }}| j                  ||       y )Nc              3   N   K   | ]  }|j                   j                  d k(    yw)metaN)devicer   )r%   rG   s     r   r'   z)TensorLikePair.compare.<locals>.<genexpr>  s     Kuu||  F*Ks   #%)rj   rk   _compare_attributesany_equalize_attributes_compare_values)r   rj   rk   s      r   r   zTensorLikePair.compare  s`    ;;  2K8JKK44VXFVX.r   c                 >    dt         dt        dt        dt        f fd}|j                  |j                  k7  r |d|j                  |j                         |j                  |j                  k7  r |d|j                  |j                         nS|j                  rG|j                         |j                         k7  r& |d|j                         |j                                |j                  |j                  k7  r+ j                  r |d	|j                  |j                         np|j                  t        j                  k(  rS j                  rG|j                         |j                         k7  r& |d
|j                         |j                                 j                  r7|j                  |j                  k7  r |d|j                  |j                          j                  r9|j                  |j                  k7  r |d|j                  |j                         yyy)a  Checks if the attributes of two tensors match.

        Always checks

        - the :attr:`~torch.Tensor.shape`,
        - whether both inputs are quantized or not,
        - and if they use the same quantization scheme.

        Checks for

        - :attr:`~torch.Tensor.layout`,
        - :meth:`~torch.Tensor.stride`,
        - :attr:`~torch.Tensor.device`, and
        - :attr:`~torch.Tensor.dtype`

        are optional and can be disabled through the corresponding ``check_*`` flag during construction of the pair.
        attribute_nameactual_valueexpected_valuer   c           
      F    j                  t        d|  d| d| d       y )NzThe values for attribute 'z' do not match: r   rN   )r   r   )r  r  r  r   s      r   raise_mismatch_errorz@TensorLikePair._compare_attributes.<locals>.raise_mismatch_error  s2     JJ,^,<<L\NZ^_m^nnopr   rv   is_quantizedz	qscheme()r  zstride()r  r@   N)r#   r   r   rv   r  qschemer  r   r=   r  r   strider   r  r   r@   )r   rj   rk   r  s   `   r   r  z"TensorLikePair._compare_attributes  s   .		/2	DG		 <<8>>) &,,G("7"77  3 3X5J5J   V^^%59I9I9K%K fnn.>@P@P@RS==HOO+  $Xv}}hooNMMU]]*!!8??#44 V]]_hoo>OP(//!A 6==(//J > &,,G !?r   c                    |j                   s|j                   r |j                         }|j                         }|j                  |j                  k7  r |j                         }|j                         }|j                  |j                  k7  r|j                  }|j                  }|t        j
                  t        j                  t        j                  fv rt        j                  }|t        j
                  t        j                  t        j                  fv rt        j                  }t	        j                  ||      }|j                  |      }|j                  |      }|j                  |j                  k7  r^|j                  t        j                  k7  r|j                         n|}|j                  t        j                  k7  r|j                         n|}||fS )a_  Equalizes some attributes of two tensors for value comparison.

        If ``actual`` and ``expected`` are ...

        - ... not on the same :attr:`~torch.Tensor.device`, they are moved CPU memory.
        - ... not of the same ``dtype``, they are promoted  to a common ``dtype`` (according to
            :func:`torch.promote_types`).
        - ... not of the same ``layout``, they are converted to strided tensors.

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

        Returns:
            (Tuple[Tensor, Tensor]): Equalized tensors.
        )is_mpscpur  r@   r=   uint64uint32uint16r   promote_typesr   r  r  to_dense)r   rj   rk   actual_dtypeexpected_dtyper@   s         r   r  z#TensorLikePair._equalize_attributes  sC   , ==HOOZZ\F||~H==HOO+ZZ\F||~H<<8>>)!<<L%^^N ellELLII${{%,,ell!KK!&''nEEYYu%F{{5)H==HOO+*0--5==*HV__&fF'/%--'G!!#X  xr   c                    |j                   r| j                  }n|j                  r| j                  }n|j                  t
        j                  t
        j                  t
        j                  t
        j                  hv r| j                  }nV|j                  t
        j                  k(  r-|j                         |j                         }}| j                  }n| j                  } |||| j                  | j                  | j                          y )NrK   rL   r   )r  _compare_quantized_values	is_sparse_compare_sparse_coo_valuesr  r=   r  r	  r
  r  !_compare_sparse_compressed_valuesr  values_compare_regular_values_closerK   rL   r   )r   rj   rk   
compare_fns       r   r  zTensorLikePair._compare_values7  s    77J88J]]	
 
 ??J]]ell*%}}0AHF;;J;;JH499499	
r   c                j    | j                  |j                         |j                         |||d       S )a  Compares quantized tensors by comparing the :meth:`~torch.Tensor.dequantize`'d variants for closeness.

        .. note::

            A detailed discussion about why only the dequantized variant is checked for closeness rather than checking
            the individual quantization parameters for closeness and the integer representation for equality can be
            found in https://github.com/pytorch/pytorch/issues/68548.
        c                 (    d| j                          S )Nz
Quantized )lower)rU   s    r   <lambda>z:TensorLikePair._compare_quantized_values.<locals>.<lambda>d  s    J?Q?W?W?Y>Z2[ r   rK   rL   r   rQ   )r.  
dequantizer   rj   rk   rK   rL   r   s         r   r)  z(TensorLikePair._compare_quantized_valuesM  s@    " 11![ 2 
 	
r   c                .   |j                         |j                         k7  r8| j                  t        d|j                          d|j                                 |j                         |j                         k7  r8| j                  t        d|j                          d|j                                 | j	                  |j                         |j                         d       | j                  |j                         |j                         |||d       y)	zCompares sparse COO tensors by comparing

        - the number of sparse dimensions,
        - the number of non-zero elements (nnz) for equality,
        - the indices for equality, and
        - the values for closeness.
        zFThe number of sparse dimensions in sparse COO tensors does not match: r   zEThe number of specified values in sparse COO tensors does not match: zSparse COO indicesri   zSparse COO valuesr4  N)
sparse_dimr   r   _nnz_compare_regular_values_equal_indicesr.  _valuesr6  s         r   r+  z)TensorLikePair._compare_sparse_coo_valuesg  s      ("5"5"77JJ\((*+40C0C0E/FH ;;=HMMO+JJ[{{}oT(--/):< 	**OO+ 	+ 	

 	**NN* 	+ 	
r   c          
         t         j                  dt         j                  j                  t         j                  j                  ft         j
                  dt         j                  j                  t         j                  j                  ft         j                  dt         j                  j                  t         j                  j                  ft         j                  dt         j                  j                  t         j                  j                  fi|j                     \  }}}|j                         |j                         k7  r;| j                  t        d| d|j                          d|j                                  ||      }	 ||      }
t        j                  |	j                  |
j                        }| j!                  |	j#                  |      |
j#                  |      d| d	|j$                   
       | j!                   ||      j#                  |       ||      j#                  |      d| d	|j$                   
       | j'                  |j)                         |j)                         |||d| d       y)zCompares sparse compressed tensors by comparing

        - the number of non-zero elements (nnz) for equality,
        - the plain indices for equality,
        - the compressed indices for equality, and
        - the values for closeness.
        CSRCSCBSRBSCz)The number of specified values in sparse z tensors does not match: r   zSparse  ri   z valuesr4  N)r=   r  r>   crow_indicescol_indicesr	  ccol_indicesrow_indicesr
  r  r  r9  r   r   r#  r@   r:  r   r.   r.  r-  )r   rj   rk   rK   rL   r   format_namecompressed_indices_methodplain_indices_methodactual_compressed_indicesexpected_compressed_indicesindices_dtypes               r   r,  z0TensorLikePair._compare_sparse_compressed_values  s5   " ))((
 ))((
 ))((
 ))((!H
* --+HD.0D. ;;=HMMO+JJ?}Le{{}oT(--/):< %>f$E!&?&I#++%++-H-N-N
 	**%((7'**=9 Q/H/Q/Q.RS 	+ 	

 	** (++M: *--m< Q/C/L/L.MN 	+ 	

 	**MMOOO W5 	+ 	
r   )r   rQ   rQ   c                2    | j                  ||dd||       y)z.Checks if the values of two tensors are equal.r   r4  N)r.  )r   rj   rk   r   rQ   s        r   r:  z,TensorLikePair._compare_regular_values_equal  s$     	**H11	j 	+ 	
r   ri   c                P   t        j                  |||||      }t        j                  |      ry|j                  t        j                  g       k(  r-t        |j                         |j                         |||      }nt        ||||||      }| j                  t        |       y)zHChecks if the values of two tensors are close up to a desired tolerance.r(  N)rK   rL   rQ   )
r=   iscloser   rv   Sizerp   r&   r   r   r   )	r   rj   rk   rK   rL   r   rQ   rq   r   s	            r   r.  z,TensorLikePair._compare_regular_values_close  s     --H4di
 99W<<5::b>)*%C +'4JC 	

>3'r   c                      y)N)rK   rL   r   r   r   r   r   r   r   s    r   r   zTensorLikePair.extra_repr  s    
r   r   )r.   r/   r0   r1   r   r   r   r	   re   r   r=   r>   r   r   r   r   r  r  r  r)  r+  r,  r   r#   r   r:  r.  r
   r   r3   r4   s   @r   r   r   c  s   4 !!% $ $! !")) )
 #s(O) ) uo) uo) ) ) ) ) )  )<  %( 16sCx TX 	u||U\\)	* ")c )ell )u|| E#s(O PT /7H7H ,,7H 
	7Hr3 ll3 .3ll3 	u||U\\)	*3 j
ell 
ell 
t 
,

 ,,

 
 
 
 

4.
.
 ,,.

 .
 .
 .
 
.
`K
K
 ,,K

 K
 K
 K
 
K
d  AE

 ,,

 
 U3#(<#<=>
 

* BF(( ,,(
 ( ( ( U3#(<#<=>( 
(>	
HSM 	
r   r   )sequence_typesmapping_typesr   
pair_typesrR  rS  optionsc                   t        | |      rt        | t              st        ||      rt        |t              sst        |       }t        |      }||k7  rt        t        d| d| |      g }	t        |      D ].  }
|	j                  t        | |
   ||
   f|||g ||
d|       0 |	S t        | |      rt        ||      rt        | j                               }t        |j                               }||k7  r4||z
  }||z
  }t        t        dt        |       dt        |       |      |}t        j                  t              5  t        |      }ddd       g }	|D ].  }|	j                  t        | |   ||   f|||g ||d|       0 |	S |D ]  }	  || |fd|i|gc S  t        t&        dt%        |        dt%        |       d|      # 1 sw Y   xY w# t        $ r Y Vt        $ r  t        $ rj}t        d	|j                    d
dj#                  d |D               dt%        |       j                    d|  dt%        |      j                    d| d      |d}~ww xY w)a  Originates pairs from the individual inputs.

    ``actual`` and ``expected`` can be possibly nested :class:`~collections.abc.Sequence`'s or
    :class:`~collections.abc.Mapping`'s. In this case the pairs are originated by recursing through them.

    Args:
        actual (Any): Actual input.
        expected (Any): Expected input.
        pair_types (Sequence[Type[Pair]]): Sequence of pair types that will be tried to construct with the inputs.
            First successful pair will be used.
        sequence_types (Tuple[Type, ...]): Optional types treated as sequences that will be checked elementwise.
        mapping_types (Tuple[Type, ...]): Optional types treated as mappings that will be checked elementwise.
        id (Tuple[Any, ...]): Optional id of a pair that will be included in an error message.
        **options (Any): Options passed to each pair during construction.

    Raises:
        ErrorMeta: With :class`AssertionError`, if the inputs are :class:`~collections.abc.Sequence`'s, but their
            length does not match.
        ErrorMeta: With :class`AssertionError`, if the inputs are :class:`~collections.abc.Mapping`'s, but their set of
            keys do not match.
        ErrorMeta: With :class`TypeError`, if no pair is able to handle the inputs.
        ErrorMeta: With any expected exception that happens during the construction of a pair.

    Returns:
        (List[Pair]): Originated pairs.
    z&The length of the sequences mismatch: r   r   )rT  rR  rS  r   zKThe keys of the mappings do not match:
Missing keys in the actual mapping: z(
Additional keys in the actual mapping: Nr   zOriginating a z() at item r   c              3   4   K   | ]  }t        |g        y wr!   r"   r$   s     r   r'   z"originate_pairs.<locals>.<genexpr>  s     Kg\`CQUPVKKgr(   z with

z(): z

and

=  

resulted in the unexpected exception above. If you are a user and see this message during normal operation please file an issue at https://github.com/pytorch/pytorch/issues. If you are a developer and working on the comparison functions, please except the previous error and raise an expressive `ErrorMeta` instead.z5No comparison pair was able to handle inputs of type z and rN   )r)   r#   lenr   r   rangeextendoriginate_pairssetr   sorted
contextlibsuppressr2   r   RuntimeErrorr.   r*   r   rA   )rj   rk   rT  rR  rS  r   rU  
actual_lenexpected_lenpairsrZ   actual_keysexpected_keysmissing_keysadditional_keysr   key	pair_typer   s                      r   r\  r\    s   N 	6>*63'x08S)[
8}%8DW  $ 	CLL3KSM  *#1"/!zSz 
	 	FM	*z(M/R&++-(HMMO,-'(;6L)M9O;;A,;O:P Q>>D_>U=VX   '  + 	 $<D	   	CLL3KSM  *#1"/!zSz 
	  $ 	I!&(ErEWEFF	4 GV~UZ[_`h[iZjjkl [	  	 0 %     "$Y%7%7$8BGGKgdfKgDgChhqF|,,-T& :H~../tH: >dd
 
s+   
GG"G"	I(-I(>A%I##I(rT  rR  rS  c                N   d}	 t        | |f|||d|}g }	|D ]  }
	 |
j                           |	g}	|	j                         S # t        $ r}|j                         dd}~ww xY w# t        $ r}|	j	                  |       Y d}~jd}~wt
        $ r}t        d|
 d      |d}~ww xY w)aP  Asserts that inputs are equal.

    ``actual`` and ``expected`` can be possibly nested :class:`~collections.abc.Sequence`'s or
    :class:`~collections.abc.Mapping`'s. In this case the comparison happens elementwise by recursing through them.

    Args:
        actual (Any): Actual input.
        expected (Any): Expected input.
        pair_types (Sequence[Type[Pair]]): Sequence of :class:`Pair` types that will be tried to construct with the
            inputs. First successful pair will be used. Defaults to only using :class:`ObjectPair`.
        sequence_types (Tuple[Type, ...]): Optional types treated as sequences that will be checked elementwise.
        mapping_types (Tuple[Type, ...]): Optional types treated as mappings that will be checked elementwise.
        **options (Any): Options passed to each pair during construction.
    Trk  NzComparing

rX  )r\  r   r-   r   r?   r2   ra  pop)rj   rk   rT  rR  rS  rU  __tracebackhide__rd  
error_metaerror_metaspairr   s               r   not_close_error_metasrr    s    0 .
 ")'
 
 $&K 	LLN4 -K??A  .!!#-.  	+z**  		& `` 		s:   A A$	A!AA!$	B$-BB$BB$)	r   rK   rL   r   r   r   r   r   r   r   r   r   r   r   r   r   c       	             d}t        | |t        t        t        t        f||||||||	|
      }|r|d   j                  |
      y)a2  Asserts that ``actual`` and ``expected`` are close.

    If ``actual`` and ``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

    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 ``equal_nan`` is ``True``.

    In addition, they are only considered close if they have the same

    - :attr:`~torch.Tensor.device` (if ``check_device`` is ``True``),
    - ``dtype`` (if ``check_dtype`` is ``True``),
    - ``layout`` (if ``check_layout`` is ``True``), and
    - stride (if ``check_stride`` is ``True``).

    If either ``actual`` or ``expected`` is a meta tensor, only the attribute checks will be performed.

    If ``actual`` and ``expected`` are sparse (either having COO, CSR, CSC, BSR, or BSC layout), their strided members are
    checked individually. Indices, namely ``indices`` for COO, ``crow_indices`` and ``col_indices`` for CSR and BSR,
    or ``ccol_indices``  and ``row_indices`` for CSC and BSC layouts, respectively,
    are always checked for equality whereas the values are checked for closeness according to the definition above.

    If ``actual`` and ``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.

    ``actual`` and ``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, ``actual`` and ``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 ``check_dtype=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 ``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 ``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_layout (bool): If ``True`` (default), asserts that corresponding tensors have the same ``layout``. If this
            check is disabled, tensors with different ``layout``'s are converted to strided tensors before being
            compared.
        check_stride (bool): If ``True`` and corresponding tensors are strided, asserts that they have the same stride.
        msg (Optional[Union[str, Callable[[str], str]]]): Optional error message to use in case a failure occurs during
            the comparison. Can also passed as callable in which case it will be called with the generated message and
            should return the new message.

    Raises:
        ValueError: If no :class:`torch.Tensor` can be constructed from an input.
        ValueError: If only ``rtol`` or ``atol`` is specified.
        AssertionError: If corresponding inputs are not Python scalars and are not directly related.
        AssertionError: If ``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 ``check_layout`` is ``True``, but corresponding tensors do not have the same
            :attr:`~torch.Tensor.layout`.
        AssertionError: If only one of corresponding tensors is quantized.
        AssertionError: If corresponding tensors are quantized, but have different :meth:`~torch.Tensor.qscheme`'s.
        AssertionError: If ``check_device`` is ``True``, but corresponding tensors are not on the same
            :attr:`~torch.Tensor.device`.
        AssertionError: If ``check_dtype`` is ``True``, but corresponding tensors do not have the same ``dtype``.
        AssertionError: If ``check_stride`` is ``True``, but corresponding strided tensors do not have the same stride.
        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`` |
    +---------------------------+------------+----------+
    | :attr:`~torch.quint8`     | ``1.3e-6`` | ``1e-5`` |
    +---------------------------+------------+----------+
    | :attr:`~torch.quint2x4`   | ``1.3e-6`` | ``1e-5`` |
    +---------------------------+------------+----------+
    | :attr:`~torch.quint4x2`   | ``1.3e-6`` | ``1e-5`` |
    +---------------------------+------------+----------+
    | :attr:`~torch.qint8`      | ``1.3e-6`` | ``1e-5`` |
    +---------------------------+------------+----------+
    | :attr:`~torch.qint32`     | ``1.3e-6`` | ``1e-5`` |
    +---------------------------+------------+----------+
    | other                     | ``0.0``    | ``0.0``  |
    +---------------------------+------------+----------+

    .. 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 tolerances 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>
        Expected 1e-10 but got 1e-09.
        Absolute difference: 9.000000000000001e-10
        Relative difference: 9.0

    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):
        ...
        TypeError: No comparison pair was able to handle inputs of type
        <class 'torch.nn.parameter.Parameter'> and <class 'torch.Tensor'>.
        >>> # If the inputs are not directly related, they are never considered close
        >>> torch.testing.assert_close(actual.numpy(), expected)
        Traceback (most recent call last):
        ...
        TypeError: No comparison pair was able to handle inputs of type <class 'numpy.ndarray'>
        and <class 'torch.Tensor'>.
        >>> # 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>
        Expected nan but got nan.
        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 error 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!
        >>> # If msg is a callable, it can be used to augment the generated message with
        >>> # extra information
        >>> torch.testing.assert_close(
        ...     actual, expected, msg=lambda msg: f"Header\n\n{msg}\n\nFooter"
        ... )
        Traceback (most recent call last):
        ...
        AssertionError: Header
        <BLANKLINE>
        Tensor-likes are not close!
        <BLANKLINE>
        Mismatched elements: 2 / 3 (66.7%)
        Greatest absolute difference: 2.0 at index (1,) (up to 1e-05 allowed)
        Greatest relative difference: 1.0 at index (1,) (up to 1.3e-06 allowed)
        <BLANKLINE>
        Footer
    T)
rT  r   rK   rL   r   r   r   r   r   r   r   N)rr  r   r   r   r   r-   )rj   rk   r   rK   rL   r   r   r   r   r   r   rn  rp  s                r   assert_closert    sh    l '	
 *!!!#K( !n%%c** r   z`torch.testing.assert_allclose()` is deprecated since 1.12 and will be removed in a future release. Please use `torch.testing.assert_close()` instead. You can find detailed upgrade instructions in https://github.com/pytorch/pytorch/issues/61844.)categoryc                    t        | t        j                        st        j                  |       } t        |t        j                        s!t        j                  || j                        }|C|At        | |t        j                  dt        j                  dt        j                  di      \  }}t        j                  j                  | ||||ddd|xs d		       y)
a5  
    .. warning::

       :func:`torch.testing.assert_allclose` is deprecated since ``1.12`` and will be removed in a future release.
       Please use :func:`torch.testing.assert_close` instead. You can find detailed upgrade instructions
       `here <https://github.com/pytorch/pytorch/issues/61844>`_.
    )r@   N)r5   r5   )g-C6?r6   )r6   g:0yE>r8   TF)rK   rL   r   r   r   r   r   )r)   r=   r>   r   r@   rJ   float16float32r   testingrt  )rj   rk   rK   rL   r   r   s         r   assert_allcloserz    s    * fell+f%h-<<=|'|||

d 
MMK4  
r   )NNTr   )Dr   r   collections.abccollectionsr_  typingr   r   r   r   r   r   r	   r
   r   r   r   typing_extensionsr   r=   numpyr   r   ModuleNotFoundErrorr2   r   rw  bfloat16rx  r   	complex32	complex64r   rB   updatedictfromkeysquint8quint2x4quint4x2qint8qint32r>   r@   re   rJ   rP   r#   rf   rh   r   r   rp   r   r   ABCr   r   r   r   r   r   Mappingr\  rr  rt  FutureWarningrz  r   r   r   <module>r     sC   
       ) I	 B 
MM=	NNM	MM>	MM<	OO]	OO^	l    MM	u~~u~~u{{ELLQ%--( JN"5<<,-"tEKKue|1D$DEF" 5%<"< 	+5<<,-+
5/+ 5/+ 	c3h	+
 5%<+F >B:> ;?;; sHcUCZ$889:; C=	;
 ; 5eCHo!567; ; ; 5eCHo!567; ; 	;H >B$UG+,D#ug-. 	
  sHcUCZ$889: 	N >BGLLGllG \\G
 G G sHcUCZ$889:GTs	 sL/377 L/^L L2t  3$ 3lx
 x
vv
T v
| )4(@(@'B'2'>'>&@GGG d$	G
 $)$G s#G 	c3hG G 
$ZG\ )3}(3(@(@'B'2'>'>&@CCC d$	C
 $)$C s#C C 
)_CT "  6:N+N+N+ 	N+
 5/N+ 5/N+ N+ N+ N+ N+ N+ 
%XseSj112	3N+b e 	 ! ))) 5/) 5/	)
 ) 
) 
))O/  I	Bs   N   	N-,N-