
    uki3                        U d dl mZ d dlZd dlmZmZ d dlmZ d dlmZ d dlm	Z
 d dlmZmZ d dlZg dZd	Zd
edej$                  fdZeej$                  eez  f   Zeed<   i e
j2                  d  ej$                  ej4                        d  ej$                  e
j6                        d  ej$                  e
j8                        d  ej$                  ej:                        d  ej$                  ej<                        d  ej$                  ej>                        d  ej$                  ej@                        d  ej$                  e
jB                        d  ej$                  e
jD                        d  ej$                  ejF                        d  ej$                  ejH                        d  ej$                  ejJ                        d  ej$                  ejL                        d  ej$                  e
jN                        d ej$                  e
jP                        d ej$                  e
jR                        d ej$                  e
jT                        d ej$                  e
jV                        d ej$                  e
jX                        d ej$                  e
jZ                        d ej$                  e
j\                        d ej$                  e
j^                        d ej$                  e
j`                        d ej$                  ejb                        d ej$                  ejd                        d ej$                  ejf                        d ej$                  ejh                        d ej$                  ejj                        diZ6eed<   d Z7 ej$                  e
jN                        d ej$                  e
jP                        d ej$                  e
jR                        d ej$                  e
jT                        d ej$                  e
jV                        d ej$                  e
jX                        d ej$                  e
jZ                        d ej$                  e
j\                        d ej$                  e
j^                        d ej$                  e
j`                        d ej$                  ejb                        d ej$                  ejd                        d ej$                  ejf                        d ej$                  ejh                        d ej$                  ejj                        diZ8eed<   dede9fdZ:d/dZ;d0dej$                  deez  ez  dz  deez  fdZ<d/d Z=d/d!Z>d" Z?d# Z@d$ ZAd% ZB ee eBej                              ZC ee eBej                              ZD eed&       ZE ee eBej                              ZFd' ZGd( ZHefd)ZId* ZJddedfd+ZKddedfd,ZL	 d1d-ZMd. ZNy)2    )partialN)Any	TypeAlias)api)config)dtypes)tree_maptree_reduce)check_grads	check_jvp	check_vjpg-C6?xreturnc                     t        | d      r| j                  S t        j                  j	                  t        |             x}|S t        j                  |       j                  S )Ndtype)hasattrr   _dtypespython_scalar_types_to_dtypesgettypenpasarray)r   dts     T/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/jax/_src/public_test_util.py_dtyper   $   sN    Q77N3377Q@@MI::a=    ToleranceDictg      ?g?g{Gz?gMbP?gư>gV瞯<_default_tolerancec                      t         S N)r    r   r   default_tolerancer"   N   s    	r   gMb`?gh㈵>default_gradient_tolerancevalc                 |    t        | t        j                         xr  t        | t        t        t
        t        f      S r    )
isinstancer   genericboolintfloatcomplex)r$   s    r   is_python_scalarr,   e   s,    RZZ(	(	YZdCPW=X-YYr    c           
         | j                   |j                   cxk(  rt        j                  k(  r&n n#t        j                  j                  | ||       y t        j                  t        j                  t        j                  t        j                  t        j                  t        j                  t        j                  t        j                  t        j                  t        j                  g
fd} ||       }  ||      }i }|r||d<   |r||d<   t        j                   d      5  t        j                  j"                  | |fi |d|i d d d        y # 1 sw Y   y xY w)Nerr_msgc                 X   | j                   v r| j                  t        j                        S | j                   t        j
                  v r_| j                  t	        j                  | j                         j                  dk  rt        j                        S t        j                        S | S )Nr   )
r   astyper   float32r   _intn_dtypesiinfominint8uint8)r   custom_float_dtypess    r   maybe_upcastz,_assert_numpy_allclose.<locals>.maybe_upcastz   su    ww%%XXbjj!! 	ww'&&&XXqww!7!;!;a!?bggNNRXXNNHr   atolrtolignoreinvalidr0   )r   r   float0r   testingassert_array_equalfloat4_e2m1fnfloat8_e8m0fnufloat8_e3m4float8_e4m3float8_e4m3b11fnuzfloat8_e4m3fnfloat8_e4m3fnuzfloat8_e5m2float8_e5m2fnuzbfloat16errstateassert_allclose)abr;   r<   r0   r:   kwr9   s          @r   _assert_numpy_allcloserR   h   s   WW)7>>)JJ!!!Q!8
  1o!1o!	"	2f:	2f:	{{8$ < JJq!;r;7;< < <s   (&EE r   tolc                 4   |i n|}t        |t              s|S |j                         D ci c]  \  }}t        j                  |      | }}}t        j                  t        j                  |             } |j                  | t               |          S c c}}w r    )	r&   dictitemsr   r   r   canonicalize_dtyper   r"   )r   rS   keyvalues       r   	tolerancerZ      s}    ks#	C	J03		<*#u#	<#<

$
$RXXe_
5%	)+E2	33 	=s    Bc                    t        j                  |       t        j                  |      }} | j                  |j                  k(  sJ t        t	        | j
                  |      t	        |j
                  |            }t        t	        | j
                  |      t	        |j
                  |            }t        | ||| j                  z  ||j                  z  |       y Nr;   r<   r0   )r   r   shapemaxrZ   r   rR   size)rO   rP   r;   r<   r0   s        r   _assert_numpy_closera      s    	A

1Q!	
AGG			Yqww%y$'?	@$	Yqww%y$'?	@$AD166Mqvv!(*r   c                 D    t        t        |||      }t        || |       y r\   )r   ra   r	   )xsysr;   r<   r0   assert_closes         r   check_closerf      s"    ,4d!(*,
<R r   c                 $    d }t        || |       y )Nc                     t         j                  j                  rt        |       t        |      k(  sJ y t	        j
                  t        |             t	        j
                  t        |            k(  sJ y r    )r   
enable_x64rY   r   r   rW   r   ys     r   _assert_dtypes_matchz1_check_dtypes_match.<locals>._assert_dtypes_match   sZ    AY&)###((3((34 5 4r   r	   )rc   rd   rl   s      r   _check_dtypes_matchrn      s    5 R(r   c                 R    d }t        t        j                  t        || |            S )Nc                     t        j                  t        j                  t        j                  |       j	                  d      |j	                  d                  S )N)r   realdotconjreshaperj   s     r   contractzinner_prod.<locals>.contract   s7    77266"''!*,,R0!))B-@AAr   )r
   r   addr	   )rc   rd   rv   s      r   
inner_prodrx      s"    B	RVVXhB7	88r   c          
         t        j                  d      5  t        j                  t        j                  | |      t        j                  d|      t        j
                  | ||            cddd       S # 1 sw Y   yxY w)z1Subtraction that with `inf - inf == 0` semantics.r=   r>   r   r   N)r   rM   whereequalarraysubtract)r   rk   r   s      r   _safe_subtractr      sX    	{{8$ 488BHHQNBHHQ$6KK1E244 4 4s   AA66A?c                       fd}|S )Nc                      t        | d         }t        j                   |  |      }t        d | D              r|j	                         }|S )Nr   rz   c              3   2   K   | ]  }t        |        y wr    )r,   ).0args     r   	<genexpr>z9_preserve_input_types.<locals>.wrapped.<locals>.<genexpr>   s     
1SC 
1s   )r   r   r}   allitem)argsr   resultfs      r   wrappedz&_preserve_input_types.<locals>.wrapped   sB    47OEXXahe,F

1D
11{{}fMr   r!   )r   r   s   ` r   _preserve_input_typesr      s     
.r   c                 0    t        | |t        |             S Nrz   )r   r   rj   s     r   <lambda>r      s    q!6!9 E r   c                 &    fd}t        ||       S )Nc                     t        |       }t        j                  | t        j                  |      |      }t	        |       r|j                         S |S r   )r   r   multiplyr}   r,   r   )r   r   r   rO   s      r   mulzscalar_mul.<locals>.mul   sA    1IE[[BHHQe4EBF,Q/6;;=;V;r   rm   )rc   rO   r   s    ` r   
scalar_mulr      s    < 
#r	r   c                 *    t        j                  |      t        |       fd}t        j                  t         j
                        r" |       j                  d       |       z  z   }n |       }t        |      r|j                         S |S )Nc                  L    t        j                   j                          S r   )r   r   randn)r   rngr^   s   r   r   zrand_like.<locals>.<lambda>   s    "**YSYY.e< r   y              ?)	r   r^   r   r   
issubdtypecomplexfloatingr   r,   r   )r   r   r   r   r   r^   s   `   @@r   	rand_liker      so    
((1+%
)%
<%r112Wuzz$'%'11FWF*1-969r   c                     t        ||      } | t        ||       } | t        ||       }t        t        ||      d|z        S )Ng      ?)r   rw   subsafe_sub)r   primalstangentsepsdeltaf_posf_negs          r   numerical_jvpr      sH    
Xs
#%
S% 
!%
S% 
!%	HUE*C#I	66r   c                     | |S t        | t              s| S |j                         }| j                         D ]  \  }}||t	        j
                  |      <    |S r    )r&   rU   copyrV   r   r   )rS   defaultoutkvs        r   _merge_tolerancer      sV    [N	C	J#iik daC	*r   c                    t        |t              }t        |t              }t        j                  j	                  d      }t        t        t        |      |      } |||      \  }	}
t        |	|
        | | }t        |	|       t        | |||      }t        |	||||r| dnd       t        |
||||r| d       yd       y)	a  Check a JVP from automatic differentiation against finite differences.

  Gradients are only checked in a single randomly chosen direction, which
  ensures that the finite difference calculation does not become prohibitively
  expensive even for large input/output spaces.

  Args:
    f: function to check at ``f(*args)``.
    f_vjp: function that calculates ``jax.jvp`` applied to ``f``. Typically this
      should be ``functools.partial(jax.jvp, f))``.
    args: tuple of argument values.
    atol: absolute tolerance for gradient equality.
    rtol: relative tolerance for gradient equality.
    eps: step size used for finite differences.
    err_msg: additional error message to include if checks fail.

  Raises:
    AssertionError: if gradients do not match.
  r   r    primalprimalr]   z tangenttangentN)r   r#   r   randomRandomStater	   r   r   rn   r   rf   )r   f_jvpr   r;   r<   r   r0   r   r   v_outt_outv_out_expectedt_out_expecteds                r   r   r      s    ( 
$ :	;$	$ :	;$
		a #WY,d3'tW%,%eU#d8.e^, D's;. e^$T-4	)(De^$T.5	*F;DFr   c                    t        |t              }t        |t              }t        t        t        j
                  j                  d            } || \  }}	 | | }
t        ||
|||r| dnd       t        ||      }t        | |||      }t        ||      }t         |	t        |                  }t        ||      }t        ||      }t        |||||r| d       yd       y)	a  Check a VJP from automatic differentiation against finite differences.

  Gradients are only checked in a single randomly chosen direction, which
  ensures that the finite difference calculation does not become prohibitively
  expensive even for large input/output spaces.

  Args:
    f: function to check at ``f(*args)``.
    f_vjp: function that calculates ``jax.vjp`` applied to ``f``. Typically this
      should be ``functools.partial(jax.jvp, f))``.
    args: tuple of argument values.
    atol: absolute tolerance for gradient equality.
    rtol: relative tolerance for gradient equality.
    eps: step size used for finite differences.
    err_msg: additional error message to include if checks fail.

  Raises:
    AssertionError: if gradients do not match.
  r   r   r   r]   r   z cotangent projectionzcotangent projectionN)r   r#   r   r   r   r   r   rf   r	   r   rt   rx   )r   f_vjpr   r;   r<   r   r0   
_rand_liker   vjpfunr   r   tangent_out	cotangentcotangent_outipip_expecteds                    r   r   r     s    ( 
$ :	;$	$ :	;$y"))"7"7":;*,-%d8.e^$T-4	)(DZ&'awC8+z5))vd9o./-'=)";	2+b+Dt! ""78@'=@r   c                    	 t        |      }|xs t        }t        t        |||      t        t        |||      	d	fd	 | ||       y)a  Check gradients from automatic differentiation against finite differences.

  Gradients are only checked in a single randomly chosen direction, which
  ensures that the finite difference calculation does not become prohibitively
  expensive even for large input/output spaces.

  Args:
    f: function to check at ``f(*args)``.
    args: tuple of argument values.
    order: forward and backwards gradients up to this order are checked.
    modes: lists of gradient modes to check ('fwd' and/or 'rev').
    atol: absolute tolerance for gradient equality.
    rtol: relative tolerance for gradient equality.
    eps: step size used for finite differences.

  Raises:
    AssertionError: if gradients do not match.
  )r;   r<   r   c                     dv rZ|rd| nd} 	 t        t        j                         ||       |dkD  r( t        t        j                         ||f|dz
  |       dv rE|rd| nd} 
 t        t        j                         ||       |dkD  r fd	} |||dz
  |       d
v rH|rd| nd} 	 t        t               ||       |dkD  r t        t               ||f|dz
  |       y y y )NfwdzJVP of JVPr/      revzVJP of VJPc                  F    t        j                  g|  \  }} ||      S r    )r   vjp)r   out_primal_pyvjp_pyr   s      r   r   z0check_grads.<locals>._check_grads.<locals>.f_vjpe  s&    "%''!"3d"3
-&
&r   linzLIN of LIN)r   r   jvpr   _jvp_from_lin)r   r   orderr0   fwd_msgrev_msgr   lin_msg_check_grads
_check_jvp
_check_vjpmodess   `       r   r   z!check_grads.<locals>._check_gradsZ  s   ~'.''#EgGCGGQ'w?	WSWWa(4,	7K~'.''#EgGCGGQ'w?		' 	UD%!)W5~'.''#EgGM1-tWE	W]A.teaiQ 
 r   N)r-   )tupleEPSr   r   r   )
r   r   r   r   r;   r<   r   r   r   r   s
      `   @@@r   r   r   @  sQ    ( 
t$
s#yt$C@*yt$C@*R R, q$r   c                 F    t        j                  | g| \  }} || }||fS r    )r   	linearize)r   r   r   
primal_outf_linr   s         r   r   r   r  s/    mmA00*ex +	[	  r   )NNr-   r    ))r   r   NNN)O	functoolsr   operatortypingr   r   jax._srcr   r   r   r   jax._src.tree_utilr	   r
   numpyr   __all__r   r   r   rU   r)   r*   r   __annotations__r@   bool_int2int4r7   int16int32int64uint2uint4r8   uint16uint32uint64rC   rE   rF   rD   rG   rH   rI   rJ   rK   rL   float16r3   float64	complex64
complex128r   r"   r#   r(   r,   rR   rZ   ra   rf   rn   rx   r   r   rw   r   r   rt   r   r   r   r   r   r   r   r   r!   r   r   <module>r      s     !   & 4  4 c bhh   #+ 56y 6%NNA%BHHRXX% BHHW\\A% BHHW\\A	%
 BHHRWWq% BHHRXX% BHHRXX% BHHRXX% BHHW]]Q% BHHW]]Q% BHHRXX% BHHRYY% BHHRYY% BHHRYY% BHHW""#S%  BHHW  !4!%" BHHW  !4#%$ BHHW##$cBHHW''($BHHW""#TBHHW$$%tBHHW  !4BHHW$$%tBHHWBHHRZZ$BHHRZZ$BHHRZZ%BHHR\\DBHHR]]U;% M @
 "((7  !3
"((7
"((7
"((7!!"C
"((7%%&
"((7  !4
"((7""#T
"((7
"((7""#T
"((7d
"((2::
"((2::
"((2::
"((2<<$
"((2==4- M &Z# Z$ Z%<P4RXX 4C%K-$?$$F 4RUX]R] 4*!)94 h-hll;<h-hll;<8EGx.rww78: -0 7 $(dR #FL $(dR #@N AE0d!r   