
    ukiKs              
         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	Z	d dl
mZmZ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 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'm(Z(m)Z)m*Z*m+Z+ ejX                  e-cZ-Z.ee/   e z  dz  Z0	 	 d7	 	 	 	 	 	 	 	 	 	 	 d8dZ1 G d de      Z2	 d9	 	 	 	 	 	 	 d:dZ3	 d9	 	 	 	 	 	 	 d;dZ4d<dZ5d Z6d=dZ7d>dZ8	 d?	 	 	 	 	 d@dZ9ddddd	 	 	 	 	 	 	 	 	 	 	 	 	 dAd Z:ddddd	 	 	 	 	 	 	 	 	 	 	 	 	 dBd!Z;e*ejx                  z  Z=	 	 dCd"Z>dDd#Z?	 	 	 	 	 	 dEd$Z@ed%d%d%d%d%d%d% e)       d&	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dFd'       ZAed%d%d%d%d%d%d% e)       d&	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dGd(       ZAdddddd)d e)       d&	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dHd*ZAdId+ZBdJd,ZC ej                  d-.       G d/ d0ej                               ZF eF       ZGej                  j                  eF       ej                  j                  eF       	 	 	 	 dKd1ZKd2 ZLd3 ZM	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dLd4ZN	 	 	 	 	 	 dMd5ZO ej                  d6      ZQd-eQ_R         ej                  eQ       eQj                  eK       eLej                  eQ<   eMej                  eQ<    ej                  eOeQ      ej                  eQ<    ej                  eQeN       y)N    )annotations)CallableMappingSequenceN)Any	TypedDictNotRequiredoverload)core)dispatch)effects)util)
xla_bridge)HashableArray)
FrozenDict)ad)batching)mlir)Layout)jaxlib)
xla_client)ir)Array	ArrayLikeDeprecatedArgDuckTypedArrayShapec                4    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 containing 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)namefnplatformapi_versionkwargss        G/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/jax/_src/ffi.pyregister_ffi_targetr&   /   s'    * 
	/	/b(K 
:28
: :    c                  &    e Zd ZU dZded<   ded<   y)TypeRegistrationa  A dictionary type for registering FFI types.

  Attributes:
    type_id: A ``PyCapsule`` object containing a pointer to the
      ``XLA_FFI_TypeId``.
    type_info: An optional ``PyCapsule`` object containing a pointer to the type
      ``XLA_FFI_TypeInfo``.
  r   type_idzNotRequired[Any]	type_infoN)__name__
__module____qualname____doc____annotations__ r'   r%   r)   r)   H   s     ,r'   r)   c                    t        d      )zRegisters a custom type ID for a FFI target.

  Args:
    name: the name of the type ID. This name must be unique within the process.
    obj: a ``PyCapsule`` object encapsulating a pointer to the type ID.
    platform: the target platform.
  z?register_ffi_type_id is not supported after jaxlib version 381.
ValueError)r    objr"   s      r%   register_ffi_type_idr6   V   s     	G	I Ir'   c                2    t        j                  | ||      S )zRegisters a custom type for a FFI target.

  Args:
    name: the name of the type. This name must be unique within the process.
    type_registration: a ``TypeRegistration`` defining the external type.
    platform: the target platform.
  )r"   )r   register_custom_type)r    type_registrationr"   s      r%   register_ffi_typer:   e   s     
	(	(

 r'   c                    t        j                  |        t        j                  t	        j
                  t         j                  |              y)z]Registers an FFI target as batch partitionable.

  Args:
    name: the name of the target.
  N)r   +register_custom_call_as_batch_partitionabler   register_plugin_callbacks	functoolspartial)r    s    r%   *register_ffi_target_as_batch_partitionabler@   v   s9     88>&&
NNr'   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.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.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%   	pycapsulerN      sd    6 f&6&67***'$$'/oov
C'	$
1	..r'   c                     t         j                  j                  t         j                  j                  t        j
                              } t         j                  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_dirrX      s:    wwrwwv?@*	j)	,,r'   c                h    | t         j                  u rdS t        j                  |       j                  S Nr1   )r   abstract_tokenphysical_avalshape)avals    r%   _aval_shaper_      s+    t***N0B0B40H0N0NNr'   c                    |/t        t        t        t        t	        |                               S t        |t              r)|j                  t        d      |j                  ddd   S t        |      S )zIConvert a layout to the minor-to-major order used by the custom call API.Nz,The FFI does not support layouts with tiling)
tuplereversedrangelenr_   
isinstancer   tilingr4   major_to_minor)r^   layouts     r%   _convert_layout_for_loweringrj      sg     ^%K$5 67899&&!}} EFF  2&&=r'   Foperand_layoutsresult_layoutsbackend_configskip_ffi_layout_processingc               8     	 	 	 	 	 	 	 	 d fd}|S )a<  Build a lowering op 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.

  Note that layouts passed to this function as tuples should be in
  minor-to-major order (as expected by XLA) rather than major-to-minor as used
  by :func:`~jax.ffi.ffi_call` and ``Layout``.

  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.
    skip_ffi_layout_processing: If true, skip processing of operand and result
      layout arguments passed to the lowering rule.
  c                *   t        
      }|j                  dd       |d   dk\  rft        t               st        d      t        xs i fi |j	                         D ci c]  \  }}|t        j                  |       c}}|d<   n|rt        d|d    d      |d<   d|vr0| j                  D cg c]  }t        j                  |       c}|d<   st        t        | j                        |d<   n-t        | j                        D cg c]
  }t        |  c}|d<   t        t        | j                        |d	<   n-t        | j                        D cg c]
  }t        |  c}|d	<   d
|vrit        d | j                  D              sM| j                  D cg c]4  }t        j                  t        j                  | t!        |                  6 c}|d
<   t        j"                  	fd|i|S c c}}w c c}w c c}w c c}w c c}w )Nr#      z:When api_version > 4, backend_config must be a dictionary.rn   zaThe use of ffi_call attributes requires a custom call API version of at least 4; got api_version=.result_typesrl   rm   result_shapesc              3  X   K   | ]"  }t        j                  t        |             $ y wN)r   is_constant_shaper_   ).0r^   s     r%   	<genexpr>zDbuild_ffi_lowering_function.<locals>._lowering_op.<locals>.<genexpr>  s'      1M6:{4011Ms   (*operands)dict
setdefaultrf   r4   itemsr   ir_attribute	avals_outaval_to_ir_typemaprj   avals_inzipallshape_tensoreval_dynamic_shape_as_ivalsr_   custom_call)ctxr{   paramsr$   kvr^   argsrn   call_target_namelowering_argsrl   rm   ro   s           r%   _lowering_opz1build_ffi_lowering_function.<locals>._lowering_op   s;    - F
mQ'm!		#J~t,LHJ 	J!%""VEK\\^ TTQD$5$5a$8!8 T"Vf 
..4].C-DAGH 	H "0fV#GJ}}Ut 4 4T :Uf^%		 $'(#,,%
 ! CLL/:%
 )$/%
 ! 
	#&(#--$
  CMM>:$
 )$/$
  f$S 1M>Amm1M .M mm!% 

D<<S+dBST
U!%f_ ,JxJ6JJE !U  V%
$
!%s   # G;8HH!H$9H)r   mlir.LoweringRuleContextr{   ir.Valuer   r   returnzir.Operationr1   )r   rl   rm   rn   ro   r   r   s   `````` r%   build_ffi_lowering_functionr      s=    H,K	!,K.6,KBE,K,K ,K\ 
r'   c               8     	 	 	 	 	 	 	 	 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.

  Note that layouts passed to this function as tuples should be in
  minor-to-major order (as expected by XLA) rather than major-to-minor as used
  by :func:`~jax.ffi.ffi_call` and ``Layout``.

  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.
    skip_ffi_layout_processing: If true, skip processing of operand and result
      layout arguments passed to the lowering rule.
  c           	     R     t        f	d| g|i |}|j                  S )Nrk   )r   results)
r   r{   r   resultrn   r   r   rl   rm   ro   s
       r%   	_loweringzffi_lowering.<locals>._lowering4  sZ    ('%%#=  
     F >>r'   )r   r   r{   r   r   r   r   z'Sequence[ir.Value | Sequence[ir.Value]]r1   )r   rl   rm   rn   ro   r   r   s   `````` r%   ffi_loweringr     s6    H	!.6BE.  
r'   c                &    t        d | D              S )Nc              3  F   K   | ]  }t        j                  |        y wrw   )r   shaped_abstractifyry   rs     r%   rz   z _result_avals.<locals>.<genexpr>J  s     ;at&&q);s   !rb   )r   s    r%   _result_avalsr   H  s    	;7;	;;r'   c                    t        | t        j                        rt        |t        j                        ryt        | dd      t        |dd      k7  ryt        | dd      t        |dd      k7  ryy)NTr]   r1   Fdtype)rf   r   AbstractTokengetattr)abs     r%   _check_compatible_avalsr   L  sa    4%%&:a9K9K+LQ7B 77Q7B 77	r'   c                :    t        d t        | |      D              S )Nc              3  n   K   | ]-  \  }}t        ||t        |t              r|n|d d d          / y w)Nra   )rj   rf   r   )ry   r^   ri   s      r%   rz   z0_convert_layouts_for_ffi_call.<locals>.<genexpr>Y  sA      / $ #
Nj&@&dd|/s   35)rb   r   )avalslayoutss     r%   _convert_layouts_for_ffi_callr   V  s'     
 / eW-/ 
/ /r'   .)has_side_effectvmap_methodinput_layoutsoutput_layoutsinput_output_aliasescustom_call_api_versionlegacy_backend_config
vectorizedc                    y rw   r1   
target_nameresult_shape_dtypesr   r   r   r   r   r   r   r   s
             r%   ffi_callr   c       r'   c                    y rw   r1   r   s
             r%   r   r   t  r   r'   rr   c               2    t        |	t              st        d      g d}
|
vrt        d|
 d       t        t              r|dt	              ndt	        g      |fdk\  rt        d d	      d fd
}|S )a  Call a foreign function interface (FFI) target.

  See the :ref:`ffi-tutorial` tutorial for more information.

  Like :func:`~jax.pure_callback`, the behavior of ``ffi_call`` under
  :func:`~jax.vmap` depends on the value of ``vmap_method``. See the
  :func:`~jax.pure_callback` documentation for more details about the allowed
  values and examples of their behavior.

  The current default behavior is to use ``vmap_method="sequential"`` when
  not specified, but this behavior is deprecated, and in the future, the
  default will be to raise a ``NotImplementedError`` unless ``vmap_method`` is
  explicitly specified.

  Args:
    target_name: the name of the XLA FFI custom call target that was registered
      using :func:`~jax.ffi.register_ffi_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``.
      ``jax.core.abstract_token`` may be used to represent a token-typed output.
    has_side_effect: boolean specifying whether the custom call has side
      effects. When ``True``, the FFI call will be executed even when the
      outputs are not used.
    vmap_method: string specifying how the FFI call transforms under
      :func:`~jax.vmap` as described above.
    input_layouts: a sequence of layouts for each input argument. In each case,
      the layout can be (a) ``None`` indicating that this input is in default
      row-major order, (b) a ``Layout`` specifying the axis order,
      or (c) a sequence of integers specifying the major-to-minor axis
      ordering. Users who are familiar with XLA layouts should note that this
      function expects layouts in major-to-minor order instead of the
      minor-to-major order that XLA uses. For example, a batch of row-major
      matrices could be specified using the layout ``[0, 1, 2]``, whereas a
      batch of column-major matrices would have layout ``[0, 2, 1]``. In both
      of these examples, the leading/batch dimension is the "slowest" axis. The
      ``input_layouts`` parameter should be used to request the memory layout
      expected by the FFI call target, and XLA will ensure that the buffers
      have the correct layouts before the handler is executed.
    output_layouts: like ``input_layouts``, but specifying the required layouts
      for the output arrays.
    input_output_aliases: a dictionary where the keys are input indices and the
      values are output indices. This mapping indicates which output arrays
      alias specific input arrays.
    custom_call_api_version: the version number of the custom call API
      implemented by the FFI target ``target_name``. The only formally
      supported version is the typed FFI API with ``custom_call_api_version=4``,
      but earlier unsupported custom calls can be executed using this argument.
    legacy_backend_config: for legacy targets implemented using
      ``custom_call_api_version<4``, attributes are passed using the opaque
      string representation provided by this argument. This parameter cannot be
      used with ``custom_call_api_version>=4``.

  Returns:
    A function that can be called with the input arrays as positional arguments
    to execute the FFI handler. Any keyword arguments are passed as named
    attributes to the FFI handler using XLA's FFI interface.
  zcThe 'vectorized' argument of jax.ffi.ffi_call was removed in JAX v0.6.0. Use 'vmap_method' instead.)
sequentialsequential_unrolledexpand_dimsbroadcast_alllegacy_vectorizedNz.vmap_method must be on of the allowed methods z, but got: TFrr   zYThe use of the legacy_backend_config parameter requires custom_call_api_version < 4; got rs   c                    | D cg c]  }t        j                  |       }}t        t        t        |            }nGt              t        |      k7  r$t        dt        |       dt               d      t        |      }t        t        t                    }nGt              t              k7  r$t        dt               dt               d      t              }d}t        j                               D ]  \  }}t        |      t        |      }}|t        |       k\  r!t        d| d| d	| d
t        |        d	      |t              k\  r!t        d| d| d| d
t               d	      ||   }	|   }
t        |	|
      st        d| d| d|	 d|
 d	      ||   ||   k7  rt        d| d| d||    d||    d	      |||ffz  } t        j                  |  } t        j                  | |||t        |      d
}rt!        t              rt        |      S |S |d   S c c}w )NzThe number of input arguments (z*) must equal the number of input layouts (z).zThe number of outputs (z+) must equal the number of output layouts (r1   z+input_output_aliases contains the mapping ':z' with input index z outside the range [0, z' with output index z,' referring to an input with abstract value z/ and an output with a different abstract value rs   z$' referring to an input with layout z' and an output with a different layout )
result_avalsr   r   r   r   r   r   r   r   
attributesr   )r   get_avalrb   r   rj   re   r4   r   sortedr~   intr   standard_insert_pvary
ffi_call_pbind_wrap_kwargs_hashablerf   )r   r$   xin_avalsstatic_input_layoutsstatic_output_layoutsstatic_input_output_aliasesi_idxo_idxin_avalout_avalr   r   r   r   r   r   multiple_resultsoutput_layouts_r   r   r   r   s               r%   wrappedzffi_call.<locals>.wrapped  s   *./Qa /H/"3'CX#NO	]	s8}	,-c(m_ =((+M(:';2?@ 	@ ;8;HJ#C(D(4%6 7 
_	\!2	2%c,&7%8 9)),_)=(>bBC 	C <L<KM @B' !5!;!;!=> 9,%5z3u:uCI;E7!E7 K""'(?T2    C%%;E7!E7 K##(')@\"#2'( ( 5/&&w9;E7!E7 K;;B) D88@zDE E  &*?*FF;E7!E7 K33G3N2O P7&u-.a12 2
 	$'88#394 %%t,Doo	!'*,8 73(0G 	'	/W~nQZK 0s   H?)r   r   r$   r   )rf   r   r4   r   r   )r   r   r   r   r   r   r   r   r   r   allowed_vmap_methodsr   r   r   r   s   ````` ```   @@@r%   r   r     s    R 
J	.
	-. .F,,

89M8N O=	"# #
 #X.$O !45L "5!67L%'O!&;&G
	,,C+DA	GH HF FP 
.r'   c                   g }t        | j                               D ]  \  }}t        |t        j                        r|j                  |t        |      f       =t        |t              r|j                  |t        |      f       j	 t        |       |j                  ||f        t        |      S # t        $ r}t        d| d|       |d }~ww xY w)Nz*Non-hashable keyword argument to ffi_call z: )r   r~   rf   npndarrayappendr   r|   r   hash	TypeErrorrb   )r$   hashable_kwargsr   r   es        r%   r   r   8  s    +-/V\\^$ 'da!RZZ aq!123	At	aA/0'Q
 	1v&' 
	  J82aSACHI	JJs   B22	C;CCc                    i }| D ]J  \  }}t        |t              r|j                  ||<   &t        |t              r|j                  ||<   F|||<   L |S rw   )rf   r   valr   _d)r$   unwrapped_kwargsr   r   s       r%   _unwrap_kwargs_hashabler   J  s`    %' da!]#EEq	Az	"DDqq 
r'   T)frozenc                      e Zd Zd Zy)	FfiEffectc                     y)NFFIr1   )selfs    r%   __str__zFfiEffect.__str__X  s    r'   N)r,   r-   r.   r   r1   r'   r%   r   r   V  s    r'   r   c                    t        j                  dg|  |rt        hnt         j                  }t	        d | D              |fS )Nr   c              3     K   | ]h  }|t         j                  u r|nO|j                  |j                  j                  j
                  rt        j                         n|j                          j yw))shardingN)r   r[   updater   meshemptyget_cur_mesh_shardingr   s     r%   rz   z)ffi_call_abstract_eval.<locals>.<genexpr>i  se      &  ,,,qxx%&ZZ__%:%: #'"<"<">@A

  MM &s   A.A0)r   standard_vma_rule
_FfiEffect
no_effectsrb   )r   r   r   _r   s        r%   ffi_call_abstract_evalr   a  sL     /h/+ZL'	 & %& 
& (/
/ /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.r3   r   r   r   s      r%   ffi_call_jvpr   o  '    
+ 'I I	J Jr'   c                "    ~t        d|  d      r   r3   r   s      r%   ffi_call_transposer  v  r   r'   c          	     b    t        ||||t        |      ||      } || g|	i t        |      S )N)r   rl   rm   operand_output_aliasesr#   rn   )r   r|   r   )r   r   r   r   r   r   r   r   r   r{   r   rules               r%   ffi_call_loweringr  }  sD     
k?&3%3-12F-G"9%:
<$ 
c	DH	D 7
 C	DDr'   c          	         ddl m} ddl m} t        ||      D 	ch c]&  \  }}	|	t        j
                  ur|j                  |	   ( c}	}\  t        ||      D 
cg c]0  \  }
}|t        j
                  u r|
nt	        j                  |
|d      2 }}
}t        fdD              }dvr)j                  d      t        d d   D              d<   dk(  rJj                  d	      "t        d
 t        d	   |      D              d	<     j                  ||d}n!dk(  sdk(  rdk(  rnd}t        ||      D 	cg c],  \  }}	|	t        j
                  u r|j                  ||f      n|. }}}	j                  d	      t        d d	   D              d	<     j                  ||d}ndk(  sdk(  rf|D 	cg c]  }	|	t        j
                  u c}	t        j                  |      \  } fddk(  }fd}|j                  |d||      \  }}nt        d j                    dd      t        |      dt#        |      z  fS c c}	}w c c}}
w c c}	}w c c}	w )Nr   )control_flow)laxc              3  L   K   | ]  }t        j                  d |        yw)r   N)r   unmapped_aval)ry   r^   	axis_sizes     r%   rz   z$ffi_batching_rule.<locals>.<genexpr>  s'      G15dAt,Gs   !$)r   r   r   c              3  N   K   | ]  }|d nt        d |D              dz     y w)Nc              3  &   K   | ]	  }|d z     yw   Nr1   ry   ns     r%   rz   z.ffi_batching_rule.<locals>.<genexpr>.<genexpr>  s     )@A!a%)@   r   r   ry   ri   s     r%   rz   z$ffi_batching_rule.<locals>.<genexpr>  s1      %0 E)@)@$@4$GG%0   #%r   r   c              3  |   K   | ]4  \  }}|t         j                  u r|n|d nt        d |D              dz    6 y w)Nc              3  &   K   | ]	  }|d z     ywr  r1   r  s     r%   rz   z.ffi_batching_rule.<locals>.<genexpr>.<genexpr>  s     ,CqQU,Cr  r  )r   
not_mappedrb   )ry   ri   ds      r%   rz   z$ffi_batching_rule.<locals>.<genexpr>  sJ      &? fa ,,,&>4u,CF,C'Cd'JL&?s   :<)r   r   r   r   r  c              3  N   K   | ]  }|d nt        d |D              dz     y w)Nc              3  &   K   | ]	  }|d z     ywr  r1   r  s     r%   rz   z.ffi_batching_rule.<locals>.<genexpr>.<genexpr>  s     +BaAE+Br  r  r   r  s     r%   rz   z$ffi_batching_rule.<locals>.<genexpr>  s1      &1 .$e+B6+B&BT&I
I&1r  r   r   c                \    t        j                  |       } j                  |dS )N)r   r   )r   merge_listsr   )batched_argsmerged_args
is_batchedr$   primr   unbatched_argsr   s     r%   
_batch_funz%ffi_batching_rule.<locals>._batch_fun  s=    $$ZNkTYY#! 	 r'   c                    d |      fS rZ   r1   )r   r   r#  s     r%   <lambda>z#ffi_batching_rule.<locals>.<lambda>  s    b*Q-( r'   r1   )unrollzvmap is only supported for the z primitive when vmap_method is one of 'sequential', 'sequential_unrolled', 'expand_dims', 'broadcast_all', or 'legacy_vectorized'. Got vmap_method=rs   r  )jax._src.laxr  r  r   r   r  r]   moveaxisrb   getr   	broadcastr   partition_listscanNotImplementedErrorr    re   )r!  r   dimsr   r   r$   r  r  r   r  argdimnew_argsbatched_result_avalsoutvalssizer   
bcast_argsr  r&  gr   r#  r  r   r"  s   `  ```                @@@@r%   ffi_batching_ruler7    s    ('*4 1tq!H/// 
 1*) >At_N19c H///cS!,- N( N G9EG G >>jj!".$ %0-.%0  0F '' zz/". % &? vo6=&? !?f_ dii	) 	G m#{o'E#69AD $')Aq &'(*=*=%=a$!1D)J ) zz/". % &1/&1 !1f_ dii' 		G l"k5J&J8<=1!8...=J#'#6#6z8#L NL  11F(A""1b,v"FJAw

)$)) 5E8C~Q	HI I 
wG,	,,C1N>) >s   +I&$5I,1I2I8r   )cpur  )r    strr!   r   r"   r9  r#   r   r$   r   r   None)r8  )r    r9  r5   r   r"   r9  r   r:  )r    r9  r9   r)   r"   r9  r   r:  )r    r9  r   r:  )r   r9  )r^   core.AbstractValuer   r   rw   )r^   r;  ri   FfiLayoutOptionsr   zSequence[int])r   r9  rl   !Sequence[FfiLayoutOptions] | Nonerm   r=  rn   'Mapping[str, ir.Attribute] | str | Nonero   boolr   r   r   zCallable[..., ir.Operation])r   r9  rl   r=  rm   r=  rn   r>  ro   r?  r   r   r   zmlir.LoweringRule)r   Sequence[ResultMetadata]r   tuple[core.AbstractValue, ...])r   r;  r   r;  r   r?  )r   zSequence[core.AbstractValue]r   zSequence[FfiLayoutOptions]r   ztuple[Sequence[int], ...])r   r9  r   ResultMetadatar   r?  r   
str | Noner   r=  r   4FfiLayoutOptions | Sequence[FfiLayoutOptions] | Noner   dict[int, int] | Noner   r   r   rC  r   bool | None | DeprecatedArgr   zCallable[..., Array])r   r9  r   r@  r   r?  r   rC  r   r=  r   rD  r   rE  r   r   r   rC  r   rF  r   zCallable[..., Sequence[Array]])r   r9  r   z)ResultMetadata | Sequence[ResultMetadata]r   r?  r   rC  r   r=  r   rD  r   rE  r   r   r   rC  r   rF  r   z&Callable[..., Array | Sequence[Array]])r$   dict[str, Any]r   Sequence[tuple[str, Any]])r$   rH  r   rG  )r   rA  r   r?  )r   r   r{   r   r   r9  r   r?  r   Sequence[Sequence[int]]r   rI  r   zSequence[tuple[int, int]]r   r   r   rC  r   rH  r   zSequence[ir.Value])r   rC  r   zSequence[core.ShapedArray]r$   r   )Z
__future__r   collections.abcr   r   r   rB   dataclassesr>   rQ   typingr   r   r	   r
   numpyr   jax._srcr   r   r   r   r   jax._src.hashable_arrayr   jax._src.frozen_dictr   jax._src.interpretersr   r   r   jax._src.layoutr   jax._src.libr   r   jax._src.lib.mlirr   jax._src.typingr   r   r   r   r   safe_mapr   
unsafe_mapr   r<  r&   r)   r6   r:   r@   rN   rX   r_   rj   r   r   r   rB  r   r   r   r   r   r   	dataclassEffectr   r   lowerable_effectsadd_typecontrol_flow_allowed_effectsr   r   r  r  r7  	Primitiver   r   simple_impldef_effectful_abstract_evalprimitive_jvpsprimitive_transposesr?   primitive_batchersregister_loweringr1   r'   r%   <module>re     s   # 7 7    	 8 8       1 + $ * & "  #  $ $ --ZC=6)D0  	:
:: : 	:
 : 
:2y " I
I	I I 
	I$ 
'  
	"	/D-O
 :>


&6
BO
  :>8<>B',RR 7R 6	R
 <R !%R R !Rp :>8<>B',22 72 6	2
 <2 !%2 2 2j  $"4"44<5<	/'	/'	/,E	/ 

  !7:KN25#&(+.;o' 	
  5 I 0 ! & ,  
  

  !7:KN25#&(+.;o1 	
  5 I 0 ! & , $ 
( ""7;KO26#$(,.;okkBk 	k
 k 5k Ik 0k !k &k ,k ,kf $	 d#  $
 [
    " "9 -  $ $ - -i 8/0/ /JJE	!EE E 	E
 +E ,E 4E !E &E *E E,M-
 M- -M- M-` T^^J'
"
    Z   
 & &'= > ,  * &8  
 #*;)*;*;z+#  J '   z#4 5r'   