
    VpfkH                       d Z ddlmZ ddlmZmZ ddlZddlZddlZddl	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 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 ddlmZ ddlmZ ddlmZ ddl Z! ej"        e#          Z$ ej%        d          Z&de&_'        ej(        )                    e&           ej*        ecZZ+ ej,        d           G d d                      Z-d=dZ.e&/                     ej0        ej1        e&                     e&j2        d=d            Z3d Z4e4ej5        e&<   d  Z6e6ej7        e&<   d>d%Z8 ej0        e8e&          ej9        e&<   d?d&Z:d@d'Z; ej<        e&e;           d( Z=dd)d*dAd.Z> ej%        d/          Z?de?_'        ej(        )                    e?            G d0 d1ej@                  ZA G d2 d3ej@                  ZB eA            ZC eB            ZDejE        F                    eA           ejE        F                    eB           ejG        F                    eA           ejG        F                    eB           ejH        F                    eB           ejI        F                    eB           dBd5ZJe?/                     ej0        ej1        e?                     e?jK        dBd6            ZLd7 ZMeMej5        e?<   d8 ZNeNej7        e?<   d9 ZOeOej9        e?<   d: ZP ej<        e?eP           dd)d;dCd<ZQdS )DzModule for JAX callbacks.    )annotations)CallableSequenceN)Any)core)dispatch)dtypes)effects)sharding_impls)	tree_util)util)ad)batching)mlir)map)
xla_client)SingleDeviceShardingpure_callbackT)frozenc                  0    e Zd ZU dZded<   ded<   dd
ZdS )_FlatCallbacka/  A Python function callable with flat arguments and results.

  An instance of this class is used as a parameter for the callback primitives.
  We prefer it to an anonymous flattened function because it produces
  equal objects when we call the same Python function with the same argument
  structure.
  Callable[..., Any]callback_funcztree_util.PyTreeDefin_tree	flat_args	jax.ArrayreturnSequence[jax.Array]c                z    t          j        | j        |          \  }}t          j         | j        |i |          S N)r   tree_unflattenr   tree_leavesr   )selfr   argskwargss       Q/var/www/html/nettyfy-visnx/env/lib/python3.11/site-packages/jax/_src/callback.py__call__z_FlatCallback.__call__>   s>    +DL)DDLD& !3!3T!DV!D!DEEE    N)r   r   r   r   )__name__
__module____qualname____doc____annotations__r'    r(   r&   r   r   2   sT           $###F F F F F Fr(   r   callbackshardingSingleDeviceSharding | None
vectorizedboolc                   ~~~ 	 t          j        d          ^}}n"# t          $ r}t          d          |d }~ww xY wt          j        ||          }t          j        |          5  	 t          j        t          j         ||           cd d d            S # t          $ r t                              d            w xY w# 1 swxY w Y   d S )Ncpubackendzjax.pure_callback failed to find a local CPU device to place the inputs on. Make sure "cpu" is listed in --jax_platforms or the JAX_PLATFORMS environment variable.zjax.pure_callback failedjaxlocal_devicesRuntimeError
device_putdefault_devicer   tree_mapnpasarrayBaseExceptionlogger	exception)result_avalsr/   r0   r2   r$   
cpu_device_es           r&   pure_callback_implrH   C   s>    
L&u555NJ	   
	/  	 
j	)	)$
*%%  
HHdO<<           1222         4    
<7<(C*!B&B>>CCCc                    ~~ ~~|S r    r.   )r/   rD   r0   r2   avalss        r&   pure_callback_abstract_evalrL   `   s     Xx	r(   c                 $    ~ ~t          d          )NzgPure callbacks do not support JVP. Please use `jax.custom_jvp` to use callbacks while taking gradients.
ValueErrorr$   r%   s     r&   pure_callback_jvp_rulerQ   l   "    
FM	N 	N Nr(   c                 $    ~ ~t          d          )NzmPure callbacks do not support transpose. Please use `jax.custom_vjp` to use callbacks while taking gradients.rN   rP   s     r&   pure_callback_transpose_rulerT   v   rR   r(   rD   Sequence[core.ShapedArray]r%   r   c                  
 t          d t          ||          D                       
d t          ||          D             }r,t          
fdD                         j        |d}n>d |D             t	          j        |          \  } fd}	t          |	|          }t          |          dt          |          z  fS )Nc              3  R   K   | ]"\  }}|t           j        u|j        |         V  #d S r    )r   
not_mappedshape).0ads      r&   	<genexpr>z)callback_batching_rule.<locals>.<genexpr>   sE       4 4$!Qx222 71:22224 4r(   c                `    g | ]+\  }}|t           j        u r|nt          j        ||d           ,S r   r   rX   moveaxisrZ   argdims      r&   
<listcomp>z*callback_batching_rule.<locals>.<listcomp>   S     N N N19c H///ccS!,,N N Nr(   c              3  Z   K   | ]%}t          j        t           j        d |          V  &dS )r   N)r   unmapped_avalno_axis_name)rZ   aval	axis_sizes     r&   r]   z)callback_batching_rule.<locals>.<genexpr>   sK       " " 	9d&7DAA" " " " " "r(   )r2   rD   c                *    g | ]}|t           j        uS r.   r   rX   rZ   r\   s     r&   re   z*callback_batching_rule.<locals>.<listcomp>   s     ===1!8..===r(   c                P    t          j        |           } j        |dS )N)rD   r2   )r   merge_listsbind)batched_argsmerged_args
is_batchedr%   primrD   unbatched_argsr2   s     r&   
_batch_funz*callback_batching_rule.<locals>._batch_fun   sE    $ZNNkTY#  	  r(   r_   )nextziptuplerq   r   partition_listlax_maplen)ru   r$   dimsr2   rD   r%   new_argsoutvalsrr   rw   rk   rt   rv   s   `  ```    @@@r&   callback_batching_ruler      s_     4 4#dD// 4 4 4 4 4)N N=@t__N N N( 0 " " " " " " " " "L di	!  	 GG >====J#'#6z8#L#L NL          j,//G	wG,	,,r(   c                4   t          | t          j                  rr| j        t	          | j        j                  k    rt          d          |t          d          t          j	                    }t          j	        j
        j        |_        |S t          | t          j                  r|t          |t                    st          dt          |                     t          t!          |j                            }| j        }|t'          d          	 |                    |          }n+# t*          $ r}t-          d| d| d          |d }~ww xY wd}t          j	                    }t          j	        j
        j        |_        d	g|_        |g|_        |S d S )
Nz~callbacks are only supported in spmd computations when all mesh axes are partitioned manually (no partial automatic sharding).zEcallbacks do not support specifying sharding inside spmd computationsz:pure_callback only supports SingleDeviceSharding, but got z9Please file a bug at https://github.com/google/jax/issuesz6Sharding provided to pure_callback specifies a device z' that is not in the device assignment ()r      )
isinstancer   SPMDAxisContextmanual_axes	frozensetmesh
axis_namesNotImplementedErrorxc
OpShardingTypeMANUALtypeShardingContextr   rx   iter
device_setdevice_assignmentAssertionErrorindex
IndexErrorrO   MAXIMALtile_assignment_dimensionstile_assignment_devices)axis_contextr0   op_shardingdevicer   device_indexrG   s          r&   _callback_op_shardingr      s   n<==  9\->-I#J#JJJL      -//K})0Kn<== "677 
!!X! !
 
 	
 D,--..f&8		"GI I 	I.(..v66 . . .&& &"& & &' ' -.	.. l
 -//K})1K./SK*+7.K' 
s   D- -
E7EEc          
         fd}t          | j        j        |          }t          j        | |d t          |          | j        | j        d|          \  }}}|S )Nc                 <    t          t          | d d          S )N)r/   r0   )rz   rH   )r   r/   paramss    r&   	_callbackz)pure_callback_lowering.<locals>._callback   s:    	
 	
 		
 	
  r(   Fhas_side_effectr0   )r   module_contextr   r   emit_python_callbacklistavals_in	avals_out)	ctxr/   r0   r$   r   r   r   resultrF   s	    `  `    r&   pure_callback_loweringr      s          &c&8&ExPP+*	

4jj	l	m	 	 	,&!Q 
-r(   c                    t          j        | j                  }t          j        |          |k    rt	          d          d S )NzQresult_shape_dtypes cannot specify 64-bit types when `jax_enable_x64` is disabled)r?   dtyper	   canonicalize_dtyperO   )shape_dtypedts     r&   _check_shape_dtyper      sJ    	x!"""r""b((
[] ] ] )(r(   F)r0   r2   r   result_shape_dtypesr$   c               J   t          j        ||f          \  }}t          j        t          |           t          j        d |          }t          j        |          \  }	}
t	          j        |t          | |          t          |	          ||d}t          j        |
|          S )a  Calls a pure Python callback. Works under :func:`jit`/:func:`~vmap`/etc.

  For more explanation, see `External Callbacks`_.

  ``pure_callback`` enables calling a Python function in JIT-ed JAX functions.
  The input ``callback`` will be passed JAX arrays placed on a local CPU, and
  it should also return JAX arrays on CPU.

  The callback is treated as functionally pure, meaning it has no side-effects
  and its output value depends only on its argument values. As a consequence, it
  is safe to be called multiple times (e.g. when transformed by :func:`~vmap` or
  :func:`~pmap`), or not to be called at all when e.g. the output of a
  `jit`-decorated function has no data dependence on its value. Pure callbacks
  may also be reordered if data-dependence allows.

  When `vmap`-ed the behavior will depend on the value of the
  ``vectorized`` keyword argument. When ``vectorized`` is ``True``, the callback
  is assumed to obey
  ``jax.vmap(callback)(xs) == callback(xs) == jnp.stack([callback(x) for x in xs])``.
  Therefore, the callback will be called directly on batched inputs (where the
  batch axes are the leading dimensions). Additionally, the callbacks should
  return outputs that have corresponding leading batch axes. If not vectorized
  ``callback`` will be mapped sequentially across the batched axis.
  For example, if ``callback = lambda x, y: np.matmul(x, y)``, then we are free
  to set ``vectorized=True`` because the ``np.matmul`` function handles
  arbitrary leading batch dimensions.

  Args:
    callback: function to execute on the host. The callback is assumed to be a pure
      function (i.e. one without side-effects): if an impure function is passed, it
      may behave in unexpected ways, particularly under transformation. The callable
      will be passed PyTrees of arrays as arguments, and should return a PyTree of
      arrays that matches ``result_shape_dtypes``.
    result_shape_dtypes: pytree whose leaves have ``shape`` and ``dtype`` attributes,
      whose structure matches the expected output of the callback function at runtime.
      :class:`jax.ShapeDtypeStruct` is often used to define leaf values.
    *args: arguments to be passed to the callback function
    sharding: optional sharding that specifies the device from which the callback should
      be invoked.
    vectorized: boolean specifying whether the callback function can operate in a
      vectorized manner.
    **kwargs: keyword arguments to be passed to the callback function

  Returns:
    result: a pytree of :class:`jax.Array` objects whose structure matches that of
      ``result_shape_dtypes``.

  See Also:
    - :func:`jax.experimental.io_callback`: callback designed for impure functions.
    - :func:`jax.debug.callback`: callback designed for general-purpose debugging.
    - :func:`jax.debug.print`: callback designed for printing.

  .. _External Callbacks: https://jax.readthedocs.io/en/latest/notebooks/external_callbacks.html
  c                @    t          j        | j        | j                  S r    r   ShapedArrayrY   r   xs    r&   <lambda>zpure_callback.<locals>.<lambda>D  s     !'22 r(   )r/   rD   r0   r2   )	r   tree_flattenr>   r   pure_callback_prq   r   rz   r!   )r/   r   r0   r2   r$   r%   r   r   rD   flat_result_avalsout_treeout_flats               r&   r   r     s    | !-tVn==)W')<===#224GI I, ) 6| D DX!Xw//*++  ( 
	!(H	5	55r(   io_callbackc                      e Zd Zd ZdS )IOEffectc                    dS )NIOr.   rF   s    r&   r   zIOEffect.<lambda>W  s    d r(   Nr)   r*   r+   __str__r.   r(   r&   r   r   V  s        N'''r(   r   c                      e Zd Zd ZdS )OrderedIOEffectc                    dS )N	OrderedIOr.   r   s    r&   r   zOrderedIOEffect.<lambda>Z  s    k r(   Nr   r.   r(   r&   r   r   Y  s        !!'''r(   r   orderedc                   ~ ~~	 t          j        d          ^}}n"# t          $ r}t          d          |d }~ww xY wt          j        ||          }t          j        |          5  	 t          j        t          j         ||           cd d d            S # t          $ r t                              d            w xY w# 1 swxY w Y   d S )Nr5   r6   zjax.io_callback failed to find a local CPU device to place the inputs on. Make sure "cpu" is listed in --jax_platforms or the JAX_PLATFORMS environment variable.zjax.io_callback failedr8   )rD   r/   r0   r   r$   rE   rF   rG   s           r&   io_callback_implr   f  s>    Hg&u555NJ	   
	/  	 
j	)	)$
*%%  
HHdO<<           /000         rI   c                2    ~~~ |rt           nt          }||hfS r    )_OrderedIOEffect	_IOEffect)r/   rD   r0   r   rK   effects         r&   io_callback_abstract_evalr     s(     Xx&5I&	x	r(   c                 $    ~ ~t          d          )Nz IO callbacks do not support JVP.rN   rP   s     r&   io_callback_jvp_ruler     s    
F5666r(   c                 $    ~ ~t          d          )Nz&IO callbacks do not support transpose.rN   rP   s     r&   io_callback_transpose_ruler     s    
F;<<<r(   c                  
 |rt          d          d |D             
d t          | |          D             }t          j        
|          \  }
fd}t	          ||          }	|	dt          |	          z  fS )Nz"Cannot `vmap` ordered IO callback.c                *    g | ]}|t           j        uS r.   rm   rn   s     r&   re   z-io_callback_batching_rule.<locals>.<listcomp>  s     ;;;,,;;;r(   c                `    g | ]+\  }}|t           j        u r|nt          j        ||d           ,S r_   r`   rb   s      r&   re   z-io_callback_batching_rule.<locals>.<listcomp>  rf   r(   c                X    t          j        |           }t          j        |ddS )NF)r/   r0   rD   r   )r   rp   io_callback_prq   )rr   mergedr/   rt   rD   r0   rv   s     r&   rw   z-io_callback_batching_rule.<locals>._batch_fun  s@    j.,GGFv8+7H H H Hr(   r_   )rO   ry   r   r{   r|   r}   )r$   r~   r/   rD   r0   r   r   rr   rw   out_valsrt   rv   s     ```     @@r&   io_callback_batching_ruler     s      ;
9
:
::;;d;;;*N N=@t__N N N(!%!4Z!J!J.,H H H H H H H H H Z..(	4#h--'	''r(   c          
        fd}t          | j        j        |          }r| j                            t
                    }t          j        | ||t          |          | j	        | j
        d|          \  }	}}
|                     t          j        t
          |i                     n7t          j        | |d t          |          | j	        | j
        d|          \  }	}}
|	S )Nc            	     >    t          t          | d d          S )N)r/   r0   r   )rz   r   )r   r/   r   r   s    r&   r   z'io_callback_lowering.<locals>._callback  s=    		
 	

 	
 	
  r(   Tr   )r   r   r   	tokens_ingetr   r   r   r   r   r   set_tokens_outTokenSet)r   r/   r0   r   r$   r   r   r   tokenr   rF   s    ` ` `     r&   io_callback_loweringr     s   	 	 	 	 	 	 	 &c&8&ExPP+ M.//E0T

	 	 	FE1 t}&6%>??@@@@0T

	 	 	FE1 
-r(   )r0   r   c               t   t          j        ||f          \  }}t          j        t          |           t          j        |          \  }}	t	          d |          }
t	          t
          j        |          }t          j        |t          | |          t          |
          ||d}t          j        |	|          S )a(  Calls an impure Python callback.

  For more explanation, see `External Callbacks`_.

  Args:
    callback: function to execute on the host. It is assumed to be an impure function.
      If ``callback`` is pure, using :func:`jax.pure_callback` instead may lead to
      more efficient execution.
    result_shape_dtypes: pytree whose leaves have ``shape`` and ``dtype`` attributes,
      whose structure matches the expected output of the callback function at runtime.
      :class:`jax.ShapeDtypeStruct` is often used to define leaf values.
    *args: arguments to be passed to the callback function
    sharding: optional sharding that specifies the device from which the callback should
      be invoked.
    ordered: boolean specifying whether sequential calls to callback must be ordered.
    **kwargs: keyword arguments to be passed to the callback function

  Returns:
    result: a pytree of :class:`jax.Array` objects whose structure matches that of
      ``result_shape_dtypes``.

  See Also:
    - :func:`jax.pure_callback`: callback designed for pure functions.
    - :func:`jax.debug.callback`: callback designed for general-purpose debugging.
    - :func:`jax.debug.print`: callback designed for printing.

  .. _External Callbacks: https://jax.readthedocs.io/en/latest/notebooks/external_callbacks.html
  c                @    t          j        | j        | j                  S r    r   r   s    r&   r   zio_callback.<locals>.<lambda>   s    D$4QWag$F$F r(   )r/   rD   r0   r   )r   r   r>   r   r   r   raise_as_much_as_possibler   rq   r   rz   r!   )r/   r   r0   r   r$   r%   r   r   flat_shape_dtypesr   r   r   s               r&   r   r     s    H !-tVn==)W')<=== ) 67J K KXFF+- -$0)<<)Xw//*++  ( 
	!(H	5	55r(   )r/   r   r0   r1   r2   r3   )r2   r3   rD   rU   r%   r   )r0   r1   )r/   r   r0   r1   )r/   r   r   r   r$   r   r0   r1   r2   r3   r%   r   )r/   r   r0   r1   r   r3   )r/   r   r   r   r$   r   r0   r1   r   r3   r%   r   )Rr,   
__future__r   collections.abcr   r   dataclasses	functoolsloggingtypingr   r9   jax._srcr   r   r	   r
   r   r   r   jax._src.interpretersr   r   r   jax._src.lax.control_flow.loopsr   r|   jax._src.libr   r   jax._src.sharding_implsr   numpyr?   	getLoggerr)   rB   	Primitiver   multiple_results%prim_requires_devices_during_loweringaddsafe_map
unsafe_map	dataclassr   rH   def_implpartialapply_primitivedef_abstract_evalrL   rQ   primitive_jvpsrT   primitive_transposesr   primitive_batchersr   r   register_loweringr   r   r   Effectr   r   r   r   lowerable_effectsadd_typecontrol_flow_allowed_effectsordered_effectsshardable_ordered_effectsr   def_effectful_abstract_evalr   r   r   r   r   r   r.   r(   r&   <module>r     s      " " " " " " . . . . . . . .                



                         # # # # # #             $ $ $ $ $ $ * * * * * * & & & & & & : : : : : : ) ) ) ) ) ) 8 8 8 8 8 8    		8	$	$ !$.11#'    . 2 2? C C C-Z d###F F F F F F F $#F    2   **8+C+:< < = = = "   #"N N N &< / "N N N ,H  (#- #- #- #-L 0Ay/@O0 0 O ,
2 2 2 2j   6  (> ? ? ?] ] ] -1J6 J6 J6 J6 J6 J6^ }--!%   . 2 2= A A A    w~   " " " " "gn " " " HJJ	"?$$    " "8 , , ,   " "? 3 3 3  $ - -h 7 7 7  $ - -o > > >       1 1 1  ! * *? ; ; ;   2   (y()A)68 8 9 9 9 *	  	  	  +*	 7 7 7 $8 -  = = = *D  &( ( ( .G M *% % %P  }&: ; ; ; -116 16 16 16 16 16 16 16r(   