
    Vpf6                       d 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
ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZmZ  ej        e            G d de          Z G d d          Z e            Z G d d          Z G d d          Z G d d          Zed6d            Zeddd7d            Zd Zd8d9d Z d:d$Z!d;d'Z" G d( d)e	          Z#d<d,Z$dd-d=d2Z% eee          d3             Z&ed4             Z'd5 Z(dS )>am  
Utilities for defining functions composed with transformations.

For example,

   from jax._src import linear_util as lu

   wf = lu.wrap_init(f)  # Produce a WrappedFun for applying transformations on `f`

A `WrappedFun` object represents a function `f`, together with a sequence of
nested transformations that are to be applied to the positional and keyword
arguments at call time and function return values at return time.
A transformation can take some static positional arguments that are given
at the wrapping time, and may also return some auxiliary output:

    wf, aux_out_thunk = trans1(wf, static_arg)

We can call the transformed function. First, the transformation is applied
to the dynamic args and keyword args to produce new dynamic and keyword args.
Then the underlying function is called and the transformation is applied to
the results.
If there are multiple transformations, they form a stack. The arguments are
transformed first with the last applied transformation; the results are
transformed first with the first applied transformation.

    res = wf.call_wrapped(dynamic_args, kwargs)
    # Now `aux_out_thunk()` is the auxiliary output.

A transformation is written as a generator function that takes zero or more
static positional arguments (given when the transformation is instantiated),
along with positional and keyword arguments to be transformed.
The generator will yield twice:

    @lu.transformation_with_aux
    def trans1(static_arg, *dynamic_args, **kwargs):
      ...
      # First yield: pair of transformed (args, kwargs). Get back the results.
      results = yield (new_dynamic_args, new_kwargs)
      ...
      # Second yield: pair of (transformed results, and auxiliary output)
      yield new_results, auxiliary_output


`WrappedFun` objects explicitly represent the set of transformations so that
they can be used as dictionary keys for memoization. `WrappedFun` objects
compare as equal only if they compute the same function. The static and the
dynamic positional arguments for the generators, and also the auxiliary output
data must be immutable, because it will be stored in function memoization tables.
    )annotations)Callable)partial)Any
NamedTupleN)config)core)traceback_util)tree_map)currycache_clearing_funsc                      e Zd ZdS )StoreExceptionN__name__
__module____qualname__     T/var/www/html/nettyfy-visnx/env/lib/python3.11/site-packages/jax/_src/linear_util.pyr   r   Q             r   r   c                      e Zd ZdS )EmptyStoreValueNr   r   r   r   r   r   T   r   r   r   c                  H    e Zd ZdZdZd Zd Zd Zed             Z	d Z
e
ZdS )	StorezHStorage for a value, with checks for overwriting or reading empty store.)_valc                    t           | _        d S N_EMPTY_STORE_VALUEr   selfs    r   __init__zStore.__init__[   s    "DIIIr   c                N    | j         t          urt          d          || _         d S )NzStore occupied)r   r    r   )r"   vals     r   storezStore.store^   s*    y***+,,,DIIIr   c                    t           | _        d S r   r   r!   s    r   resetzStore.resetc   s    "DIIIr   c                2    | st          d          | j        S )NzStore empty)r   r   r!   s    r   r%   z	Store.valg   s      *=)))9r   c                    | j         t          uS r   )r   r    r!   s    r   __nonzero__zStore.__nonzero__m   s    9...r   N)r   r   r   __doc__	__slots__r#   r&   r(   propertyr%   r+   __bool__r   r   r   r   r   W   sw        PP)# # #  
# # #   8
/ / / (((r   r   c                  :    e Zd ZdZd Zed             Zd Zd ZdS )
EqualStore)_storec                ,    t                      | _        d S r   )r   r2   r!   s    r   r#   zEqualStore.__init__u   s    ''DKKKr   c                    | j         j        S r   )r2   r%   r!   s    r   r%   zEqualStore.valx   s    ;?r   c                    	 | j                             |           d S # t          $ rD}	 t          | j         j        |k              }|st          d          d n#  |d xY wY d }~d S d }~ww xY w)Nz#Store occupied with not-equal value)r2   r&   r   boolr   )r"   r%   eokays       r   r&   zEqualStore.store|   s    	P
k P P PPDK$+,,  	PDEE4
O	PT	P 	P 	P 	P 	P 	PPs&    
A,AA'AA''A,c                8    | j                                          d S r   )r2   r(   r!   s    r   r(   zEqualStore.reset   s    Kr   N)	r   r   r   r-   r#   r.   r%   r&   r(   r   r   r   r1   r1   r   sd        )     8
P 
P 
P    r   r1   c                  X    e Zd ZdZdZd Zed             Z ddZd Zd Z	d	 Z
d
 Zd ZdS )
WrappedFuna|  Represents a function `f` to which `transforms` are to be applied.

  Args:
    f: the function to be transformed.
    transforms: a list of `(gen, gen_static_args)` tuples representing
      transformations to apply to `f.` Here `gen` is a generator function and
      `gen_static_args` is a tuple of static arguments for the generator. See
      description at the start of this module for the expected behavior of the
      generator.
    stores: a list of out_store for the auxiliary output of the `transforms`.
    params: extra parameters to pass as keyword arguments to `f`, along with the
      transformed keyword arguments.
  f
transformsstoresparamsin_type
debug_infoc                Z    || _         || _        || _        || _        || _        || _        d S r   r<   )r"   r=   r>   r?   r@   rA   rB   s          r   r#   zWrappedFun.__init__   s0    DF DODKDKDL DOOOr   c                .    t          | j        dd          S )Nr   z<unnamed wrapped function>)getattrr=   r!   s    r   r   zWrappedFun.__name__   s    46:'CDDDr   returnc                f    t          | j        ||ff| j        z   |f| j        z   | j        dd          S )z$Add another transform and its store.N)r;   r=   r>   r?   r@   )r"   gengen_static_args	out_stores       r   wrapzWrappedFun.wrap   s@    df_57$/I lT[0$+tTK K Kr   c                t    t          | j        |          D ]!\  }}||                    |j                   "dS )z5Copy the values from the `stores` into `self.stores`.N)zipr?   r&   r%   )r"   r?   
self_storeother_stores       r   populate_storeszWrappedFun.populate_stores   sI    #&t{F#;#; * *
K		)))* *r   c           	        g }t          | j        | j                  D ]I\  \  }}} ||t          |          z   i |}t	          |          \  }}|                    ||f           Jdx}x}}	  | j        |i t          | j        fi |}n6#  |r.|	                                d         
                                 |. xY wdx}}|r|	                                \  }}	 |                    |          }n6#  |r.|	                                d         
                                 |. xY w||\  }}|                    |           ||S )zCalls the underlying function, applying the transforms.

    The positional `args` and keyword `kwargs` are passed to the first
    transformation generator.
    Nr   )rM   r>   r?   tuplenextappendr=   dictr@   popclosesendr&   )	r"   argskwargsstackrH   rI   rJ   anssides	            r   call_wrappedzWrappedFun.call_wrapped   s    E-0$+-N-N % %)o	C/E$KK/;F;;c#YYldFllC#$$$$(,,C,/I
DFD8D777788cc  		A  D6
 yy{{nc9hhsmm  	!
))++a.


 
 
   	!			T   Js   .B 3B? C6 63D)c                    d }t          |t          | j                            }dd                    |          z   dz   t	          | j                  z   dz   S )Nc                Z    | \  }\  }}| dt          |           dt          |           S )Nz   : z   )fun_name)xirH   rY   s       r   transform_to_strz-WrappedFun.__repr__.<locals>.transform_to_str   s7    na#t::::(4..:::r   zWrapped function:

z
Core: )map	enumerater>   joinra   r=   )r"   rd   transformation_stacks      r   __repr__zWrappedFun.__repr__   sc    ; ; ; /4?1K1KLL 499-A#B#BBZORZ[_[aRbRbbeiiir   c                \    t          | j        | j        | j        | j        | j        f          S r   )hashr=   r>   r@   rA   rB   r!   s    r   __hash__zWrappedFun.__hash__   s.    $+t|" # # #r   c                    | j         |j         k    o?| j        |j        k    o/| j        |j        k    o| j        |j        k    o| j        |j        k    S r   )r=   r>   r@   rA   rB   )r"   others     r   __eq__zWrappedFun.__eq__   sX    Feg 0$/U5E"E 0K5<'0,0LEM,I0Ou//1r   NrF   r;   )r   r   r   r,   r-   r#   r.   rK   rP   r^   rj   rm   rp   r   r   r   r;   r;      s          O)! ! ! E E 8EK K K K
* * *) ) )Vj j j# # #1 1 1 1 1r   r;   funrF   c                0    |                     | |d          S )zAdds one more transformation to a WrappedFun.

  Args:
    gen: the transformation generator function
    fun: a WrappedFun on which to apply the transformation
    gen_static_args: static args for the generator function
  N)rK   )rH   rr   rI   s      r   transformationrt      s     
#	-	--r   F)use_eq_storeru   r6   $tuple[WrappedFun, Callable[[], Any]]c               |    |st                      nt                      fd}|                    | |          |fS )zCAdds one more transformation with auxiliary output to a WrappedFun.c                      j         S r   )r%   )rJ   s   r   <lambda>z)transformation_with_aux.<locals>.<lambda>   s	    im r   )r   r1   rK   )rH   rr   ru   rI   	out_thunkrJ   s        @r   transformation_with_auxr{      sD    
 *;egggz||)####)	#		2	2I	==r   c                >    	 | j         S #  t          |           cY S xY wr   )r   str)r=   s    r   ra   ra     s'    :q66MMMs   	 c                    |dn-t          t          |                                                    }t          | dd|dd          S )zBWraps function `f` as a `WrappedFun`, suitable for transformation.Nr   )rR   sorteditemsr;   )r=   r@   s     r   	wrap_initr     s?    22U6&,,..+A+A%B%B&	Ar2vtT	2	22r   r=   rA   core.InputType | Nonec                    | j         J || S t          |           t          | j        | j        | j        | j        || j                  S r   )rA   _check_input_typer;   r=   r>   r?   r@   rB   )r=   rA   s     r   annotater     sJ    	
			_HG	ACqx7AL	Q	QQr   core.InputTypeNonec                   t          |           t          u rt          d | D                       sJ t          d | D                       sJ d
dt          fd| D                       sJ t          d t          |           D                       sJ d | D             }| D ]N\  }}t          |          t          j        u r.|j        D ]&}t          |t          j                  r
d	||j	        <   'Ot          |          sJ d S )Nc              3  B   K   | ]}t          |          t          u V  d S r   )typerR   ).0r7   s     r   	<genexpr>z$_check_input_type.<locals>.<genexpr>  s-      'J'JQQ5(8'J'J'J'J'J'Jr   c              3     K   | ]R\  }}t          |t          j                  o0t          |          t          u ot          |t          j                   V  Sd S r   )
isinstancer	   AbstractValuer   r6   ConcreteArray)r   abs      r   r   z$_check_input_type.<locals>.<genexpr>  sx       L L;?1a 4-.. 7477d? 74#5666L L L L L Lr   rF   r6   c                Z   t          | t          j                  r(t          | j                  t
          u r| j        dk    rdS t          | t
          t          j        t          j        f          o=t          | t          j                   p"t          |           t          j        u o| j         S )Nr   T)	r   r	   DBIdxr   r%   intDArraybintshape)ds    r   
valid_sizez%_check_input_type.<locals>.valid_size  s    !TZ   T!%[[C%7%7AEQJJTq3
DK899 UAt{+++StAww$)/C/SAGVr   c              3  ~   K   | ]7\  }}t          |          t          j        u  |j        D ]} |          V  8d S r   )r   r	   DShapedArrayr   )r   r   _r   r   s       r   r   z$_check_input_type.<locals>.<genexpr>   sa        tq!$q''T=N2N2Ng 3O2N Z]]2N2N2N2N2N  r   c              3     K   | ]S\  }\  }}t          |t          j                  "|j        D ])}t          |t          j                  |j        |k     V  *Td S r   )r   r	   r   r   r   r%   )r   rc   avalr   r   s        r   r   z$_check_input_type.<locals>.<genexpr>%  s       + +<1itQ4!233+=AZ+ +891dj))+QUQY + + + + + + +r   c                    g | ]\  }}|S r   r   )r   r   r7   s      r   
<listcomp>z%_check_input_type.<locals>.<listcomp>*  s    $$$DAqa$$$r   T)rF   r6   )
r   rR   allrg   r	   r   r   r   r   r%   )rA   providedr   r   r   r   s        @r   r   r     s   	g%		C'J'J''J'J'J$J$J				 L LCJL L L 
L 
L L L LV V V V
 
    w    
 
   
 
 + +9W+=+= + + + 
+ 
+ + + +
 %$G$$$( ! !gdADzzT&&&z ! !!a$$ 	! (15/	Xr   c                  8    e Zd ZU ded<   ded<   ded<   ded<   d	S )
TracingDebugInfor}   
traced_forz
str | Nonefunc_src_infoztuple[str, ...]	arg_namesz$Callable[[], tuple[str, ...]] | Noneresult_pathsN)r   r   r   __annotations__r   r   r   r   r   3  sA          ///444444r   r   rB   TracingDebugInfo | Nonec                v    | j         J || S t          | j        | j        | j        | j        | j        |          S )z2Produce a new WrappedFun with debug_info attached.)rB   r;   r=   r>   r?   r@   rA   )r=   rB   s     r   add_debug_infor   <  s?     
			H	ACqx19j	Q	QQr   )explaincallr   r   Callable | Nonec                    t          j                    d fd}fd}j        |_        ||_        t          j        |j                   |S )aD  Memoization decorator for functions taking a WrappedFun as first argument.

  Args:
    call: a Python callable that takes a WrappedFun as its first argument. The
      underlying transforms and params on the WrappedFun are used as part of the
      memoization cache key.

  Returns:
     A memoized version of ``call``.
  rr   r;   c                |   
                     | j        i x}          }t          j        j        rUt          | j                  | j        | j        |t          j	        j        t          j
        j        t          j                    f}nG| j        | j        | j        |t          j	        j        t          j
        j        t          j                    f}|                    |d           }||\  }}|                     |           n= | g|R  }	r&t          j        j        r 	| j        ||u ||           || j        f||<   |S r   )
setdefaultr=   r   check_tracer_leaksvalue_copy_main_tracesr>   r@   rA   
enable_x64default_devicetrace_contextgetrP   explain_cache_missesr?   )rr   rY   	new_cachecachekeyresultr\   r?   r   r   
fun_cachess           r   memoized_funzcache.<locals>.memoized_funR  s6   !!#%b99E & Bs~..
CK$f&;&A!##%cc ^SZdF<M<S"(&*>*@*@BcYYsD!!Fkc6	&!!!!Dtc	 7V06 7u	)5#666$eCjJr   c                4                         | d            d S r   )rV   )r=   r   s    r   _evict_functionzcache.<locals>._evict_functiong  s    NN1dr   )rr   r;   )weakrefWeakKeyDictionaryclearcache_clearevict_functionr   add)r   r   r   r   r   s   ``  @r   r   r   E  s     +2*C*E*E*       *     (-, /,,2333	r   c                ~    t          | t          j                  r"t          j        | j        | j        fi | j        S | S r   )r   r	   	MainTracelevel
trace_typepayload)rb   s    r   r   r   p  s;    4>"" >!'1<==19===Hr   c               '     K   | i fV V  d S r   r   )rY   s    r   hashable_partialr   x  s       Rxr   c                    	  |             }	  |            }t          d          # t           $ r d|fcY S w xY w# t           $ r0 	  |            }d|fcY S # t           $ r t          d          d w xY ww xY w)Nzboth stores occupiedTFzneither store occupied)r   )aux1aux2out1out2s       r   merge_linear_auxr   }  s    3466D3TVVd 1222    4Z 
   TVVd D[  ? ? ?344$>?	s-   
: 
& 77
A4
AA4A00A4)rr   r;   rF   r;   )rr   r;   ru   r6   rF   rv   r   rq   )r=   r;   rA   r   rF   r;   )rA   r   rF   r   )r=   r;   rB   r   rF   r;   )r   r   r   r   ))r,   
__future__r   collections.abcr   	functoolsr   typingr   r   r   jax._srcr   r	   r
   jax._src.tree_utilr   jax._src.utilr   r   register_exclusion__file__	Exceptionr   r   r    r   r1   r;   rt   r{   ra   r   r   r   r   r   r   r   r   r   r   r   r   <module>r      s  0 0b # " " " " " $ $ $ $ $ $       " " " " " " " "              # # # # # # ' ' ' ' ' ' 4 4 4 4 4 4 4 4 " !( + + + & % % % %Y % % %        $_&&        6       4`1 `1 `1 `1 `1 `1 `1 `1D . . . . AF> > > > > >  3 3 3 3 3R R R R   <5 5 5 5 5z 5 5 5R R R R 9= ( ( ( ( ( (V 	(     3 3 3 3 3r   