
    Vpf)                       d dl mZ d dlmZmZmZ d dlZd dl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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mZmZm Z  d dl!Z"ej#        e$cZ$Z%	 	 dIdJdZ&d Z'dKdZ(dddd dLd)Z)dMd-Z*dNd0Z+d1d2dOd;Z,dPd>Z-d? Z.d@ Z/dQdFZ0 ej1        dG          Z2dHe2_3        e24                     ej5        ej6        e2                     e27                    e-           e.ej8        e2<   e/ej9        e2<    ej5        ee2          ej:        e2<    ej;        e2e0           dS )R    )annotations)IterableMappingSequenceN)Any)core)dispatch)dtypes)util)_check_shape_dtypecallback_batching_rule)ad)batching)mlir)jaxlib)
xla_client)ir)Array	ArrayLikeDimSizeDuckTypedArraycpu   namestrfnr   platformapi_versionintkwargsreturnNonec                ,    t          j        | |||fi |S )a  Registers a foreign function target.

  Args:
    name: the name of the target.
    fn: a ``PyCapsule`` object containing the function pointer, or a ``dict``
      where the keys are FFI stage names (e.g. `"execute"`) and the values are
      ``PyCapsule`` objects continaing a pointer to the handler for that stage.
    platform: the target platform.
    api_version: the XLA custom call API version to use. Supported versions are:
      1 (default) for the typed FFI or 0 for the earlier "custom call" API.
    kwargs: any extra keyword arguments are passed directly to
      :func:`~jaxlib.xla_client.register_custom_call_target` for more advanced
      use cases.
  )r   register_custom_call_target)r   r   r   r   r    s        S/var/www/html/nettyfy-visnx/env/lib/python3.11/site-packages/jax/_src/extend/ffi.pyregister_ffi_targetr&   (   s.    * 
	/b(K 
: 
:28
: 
: :    c                    t          j        dt           j                  }t           j        j        }t           j        |_        t           j        t           j        |f|_         || d |d                    S )a  Wrap a ctypes function pointer in a PyCapsule.

  The primary use of this function, and the reason why it lives with in the
  ``jax.extend.ffi`` submodule, is to wrap function calls from external
  compiled libraries to be registered as XLA custom calls.

  Example usage::

    import ctypes
    import jax
    from jax.lib import xla_client

    libfoo = ctypes.cdll.LoadLibrary('./foo.so')
    xla_client.register_custom_call_target(
        name="bar",
        fn=jax.extend.ffi.pycapsule(libfoo.bar),
        platform=PLATFORM,
        api_version=API_VERSION
    )

  Args:
    funcptr: A function pointer loaded from a dynamic library using ``ctypes``.

  Returns:
    An opaque ``PyCapsule`` object wrapping ``funcptr``.
  Nr   )	ctypes	CFUNCTYPE	py_object	pythonapiPyCapsule_Newrestypec_void_pc_char_pargtypes)funcptr
destructorbuilders      r%   	pycapsuler5   A   s]    6 f&677**'$'/ov
C'	$

1	.	..r'   c                     t           j                            t           j                            t          j                            } t           j                            | d          S )zIGet the path to the directory containing header files bundled with jaxlibinclude)ospathdirnameabspathr   __file__join)
jaxlib_dirs    r%   include_dirr?   c   s;    wrwv??@@*	j)	,	,,r'   )operand_layoutsresult_layoutsbackend_configcall_target_namer@   "Sequence[Sequence[DimSize]] | NonerA   rB   !Mapping[str, ir.Attribute] | Nonelowering_argsmlir.LoweringRulec               $     d
 fd	}|S )a  Build a lowering rule for an foreign function interface (FFI) target.

  By default, this lowering rule can use the input and output abstract values to
  compute the input and output types and shapes for the custom call, assuming
  row-major layouts.

  If keyword arguments are passed to the lowering rule, these are treated as
  attributes, and added to `backend_config`.

  Args:
    call_target_name: The name of the custom call target.
    operand_layouts: A sequence of layouts (dimension orders) for each operand.
      By default, the operands are assumed to be row-major.
    result_layouts: A sequence of layouts (dimension orders) for each result.
      By default, the results are assumed to be row-major.
    backend_config: Configuration data for the custom call. Any keyword
      arguments passed to the lowering rule will added to this dictionary.
    lowering_args: Any other arguments to :func:`mlir.custom_call` will also be
      passed through if provided as extra arguments to this function.
  ctxmlir.LoweringRuleContextoperandsir.Valueparamsr   r!   'Sequence[ir.Value | Sequence[ir.Value]]c                   t                    }|                    dd           t          pi fi d |                                D             |d<   d|vrd | j        D             |d<   !t	          d | j        D                       |d<   !t	          d	 | j        D                       |d
<   t          j        fd|i|j        S )Nr      c                4    i | ]\  }}|t          |          S  )_ir_attribute).0kvs      r%   
<dictcomp>z3ffi_lowering.<locals>._lowering.<locals>.<dictcomp>   s&    NNNtq!q-"2"2NNNr'   rB   result_typesc                6    g | ]}t          j        |          S rR   )r   aval_to_ir_typerT   avals     r%   
<listcomp>z3ffi_lowering.<locals>._lowering.<locals>.<listcomp>   s#    UUUt 4T : :UUUr'   c              3  $   K   | ]}|j         V  d S Nshaper[   s     r%   	<genexpr>z2ffi_lowering.<locals>._lowering.<locals>.<genexpr>   s$      2W2W$4:2W2W2W2W2W2Wr'   r@   c              3  $   K   | ]}|j         V  d S r_   r`   r[   s     r%   rb   z2ffi_lowering.<locals>._lowering.<locals>.<genexpr>   s$      1W1W$*1W1W1W1W1W1Wr'   rA   rK   )	dict
setdefaultitems	avals_out_default_layoutsavals_inr   custom_callresults)	rI   rK   rM   r    rB   rC   rF   r@   rA   s	       r%   	_loweringzffi_lowering.<locals>._lowering   s    -  F
mQ'''# P  PNNv||~~NNN P  PFV##UUs}UUUf^"22W2W#,2W2W2W"W"Wf!11W1W1W1W1W!W!Wf,JJxJ6JJRRr'   )rI   rJ   rK   rL   rM   r   r!   rN   rR   )rC   r@   rA   rB   rF   rl   s   ````` r%   ffi_loweringrm   i   sK    :S S S S S S S S S S  
r'   shapesIterable[Sequence[DimSize]]list[list[DimSize]]c                    d | D             S )Nc                z    g | ]8}t          t          t          t          |                                        9S rR   )listreversedrangelen)rT   ra   s     r%   r]   z$_default_layouts.<locals>.<listcomp>   s6    	@	@	@$xc%jj))**
+
+	@	@	@r'   rR   )rn   s    r%   rh   rh      s    	@	@	@	@	@@r'   objir.Attributec                r   t          | t                    rt          j                            |           S t          | t
                    rt          j                            |           S t          | t                    rt          j	        |           S t          | t                    rt          j                            |           S t          | d          rt          j        |           s#t!          j        |           st%          d          t          j        | j                  }t          |t          j                  r t          j                            ||           S t          |t          j                  r t          j                            ||           S t%          dt1          |                      )Ndtypez$Only scalar attributes are supportedzUnsupported attribute type: )
isinstancer   r   
StringAttrgetboolBoolAttrr   r   i64_attrfloat	FloatAttrget_f64hasattrr
   is_python_scalarnpisscalar	TypeErrordtype_to_ir_typerz   IntegerTypeIntegerAttr	FloatTypetype)rw   	mlir_types     r%   rS   rS      sh    S .=S!!!#t .;??3#s .=#u 	.<$$$sG .#C(( >BK,<,< ><===%ci00I)R^,, .^	3///	Ir|	,	, .\i---<c<<===r'   F)
vectorizedtarget_nameresult_shape_dtypes)DuckTypedArray | Sequence[DuckTypedArray]argsr   r   r~   Array | list[Array]c                   t          |t                    rd}|}nd}|f}t          t          |           t	          d |D                       }t          j        |||| d|}|r|S |d         S )a  Call a foreign function interface (FFI) target.

  Like :func:`~jax.pure_callback`, the behavior of ``ffi_call`` under
  :func:`~jax.vmap` depends on the value of ``vectorized``. When ``vectorized``
  is ``True``, the FFI target is assumed to satisfy: ``ffi_call(xs) ==
  jnp.stack([ffi_call(x) for x in xs])``. In other words, calling the FFI target
  with an extra leading dimension should return the same result as calling it
  within a loop and stacking along the zeroth axis. Therefore, the FFI target
  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 ``vectorized`` is ``False`` (the
  default behavior), transforming this ``ffi_call`` under :func:`~jax.vmap` will
  result in a :func:`~jax.lax.scan` with the ``ffi_call`` in the body.

  Args:
    target_name: the name of the XLA FFI custom call target that was registered
      using :func:`~jaxlib.xla_client.register_custom_call_target`.
    result_shape_dtypes: an object, or sequence of objects, with ``shape`` and
      ``dtype`` attributes which are expected to match the shape and dtype of
      the custom call output or outputs. :class:`~jax.ShapeDtypeStruct` is often
      used to define the elements of ``result_shape_dtypes``.
    *args: the arguments passed to the custom call.
    vectorized: boolean specifying whether the callback function can operate in
      a vectorized manner, as described above.
    **kwargs: keyword arguments that are passed as named attributes to the
      custom call using XLA's FFI interface.

  Returns:
    One or more :class:`~jax.Array` objects whose shapes and dtypes match
    ``result_shape_dtypes``.
  TFc              3  T   K   | ]#}t          j        |j        |j                  V  $d S r_   )r   ShapedArrayra   rz   )rT   xs     r%   rb   zffi_call.<locals>.<genexpr>   s3      PPat'99PPPPPPr'   )result_avalsr   r   r   )r{   r   mapr   tuple
ffi_call_pbind)	r   r   r   r   r    multiple_resultsrX   r   rk   s	            r%   ffi_callr      s    L #X.. *&LL')L,'''PP<PPPPP,O	 
 	 '  N1:r'   r   tuple[core.ShapedArray, ...]c                    ~~~~| S r_   rR   )r   r   r   ri   r    s        r%   ffi_call_abstract_evalr      s     Z	r'   c                ,    ~~t          d|  d          NzThe FFI call to `z\` cannot be differentiated. You can use `jax.custom_jvp` or `jax.custom_jvp` to add support.
ValueErrorr   r   r    s      r%   ffi_call_jvpr      6    
FI+ I I I	J 	J Jr'   c                ,    ~~t          d|  d          r   r   r   s      r%   ffi_call_transposer      r   r'   rI   rJ   rK   rL   Sequence[ir.Value]c               8    ~~ t          |          | g|R i |S r_   )rm   )rI   r   r   r   rK   r    s         r%   ffi_call_loweringr     s1     J	"k	"	"3	<	<	<	<V	<	<<r'   r   T)r   r   )r   r   r   r   r   r   r   r   r    r   r!   r"   )r!   r   )rC   r   r@   rD   rA   rD   rB   rE   rF   r   r!   rG   )rn   ro   r!   rp   )rw   r   r!   rx   )r   r   r   r   r   r   r   r~   r    r   r!   r   )r   r   r   r   r   r~   r    r   )rI   rJ   rK   rL   r   r   r   r   r   r~   r    r   r!   r   )<
__future__r   collections.abcr   r   r   r)   	functoolsr8   typingr   jax._srcr   r	   r
   r   jax._src.callbackr   r   jax._src.interpretersr   r   r   jax._src.libr   r   jax._src.lib.mlirr   jax._src.typingr   r   r   r   numpyr   safe_mapr   
unsafe_mapr&   r5   r?   rm   rh   rS   r   r   r   r   r   	Primitiver   r   def_implpartialapply_primitivedef_abstract_evalprimitive_jvpsprimitive_transposesprimitive_batchersregister_loweringrR   r'   r%   <module>r      s)   # " " " " " 7 7 7 7 7 7 7 7 7 7      				                               H H H H H H H H $ $ $ $ $ $ * * * * * * & & & & & &       # # # # # #             E E E E E E E E E E E E    -Z 	: : : : :2/ / /D- - - - ;?9=8<- - - - - -`A A A A> > > >4 	8 8 8 8 8 8v   J J JJ J J	= 	= 	= 	= T^J''
"
  
  %I%h&>
KK L L L 
  3 4 4 4 , * &8 
 #*;)*;J+( +( J '  z#4 5 5 5 5 5r'   