
    uki                         d Z ddl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c 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  ej:                  ej<                        Zej:                  defd       Z dedejB                  fdZ"de#ejH                  z  deeg df   geg df   f   fdZ%ddddejH                  dejH                  dejH                  de&e#z  dz  deeejB                  gdf   gdf   f
dZ' e	jP                  ddd      Z)e)Z*de#fd Z+d! Z,	 	 d0d#ed$ejZ                  d%ej\                  d&e/dz  fd'Z0 ejb                         dfd"ddddddd(d)eejb                  z  d#edz  d$ejZ                  d%ej\                  d*ejd                  dz  d+e#d,ejf                  dz  d-e#d&e/dz  d.e4e/e/f   dz  fd/Z5y)1zPallas helper functions.    )CallableMappingSequenceN)api)checkify)config)core)	tree_util)typing)util)conditionals)
primitives)utils)numpyxc                 0    t        j                  d |       S )a'  Create an empty PyTree of possibly uninitialized values.

  Args:
    x: A PyTree with leaves specifying the shape and dtype of
      the uninitialized object.

  Returns:
    A PyTree with the same structure as ``x``, but with uninitialized
    values.

  See Also:
    :func:`jax.lax.empty`
  c                 B    t        | j                  | j                        S N)emptyshapedtype)leafs    R/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/jax/_src/pallas/helpers.py<lambda>zempty_like.<locals>.<lambda>4   s    tzz4::)F     )r
   tree_map)r   s    r   
empty_liker   %   s     
		F	JJr   returnc                     | xt         j                  d x\    | j                  }nJ t        j                  d x\   t         j
                  j                  }n 	 t        dt        |              t        j                  t        |       |      S )zCReturns an empty array Ref with same shape/dtype/memory space as x. z empty_ref_like does not support memory_space)pl_core	MemoryRefr"   jax_coreShapeDtypeStructMemorySpaceANY
ValueErrortypenew_refr   )r   r"   s     r   empty_ref_liker,   7   st    					^^l 
		"	"	$((,,l 
%	
9$q'CDD			*Q-l	CCr   	conditionc                      fd}|S )a  Calls the decorated function when the condition is met.

  Args:
    condition: If a boolean, this is equivalent to ``if condition: f()``. If an
      array, ``when`` produces a :func:`jax.lax.cond` with the decorated
      function as the true branch.

  Returns:
    A decorator.
  c                 l    t        t              rr |         y y t        j                  | d        y )Nc                       y r   r    r    r   r   r   z(when.<locals>._wrapped.<locals>.<lambda>U   s    r   )
isinstanceboolr   cond)fr-   s    r   _wrappedzwhen.<locals>._wrappedP   s.    )T"		 
 	1l3r   r    )r-   r5   s   ` r   whenr6   C   s    4 
/r      )stepunrolllowerupperr8   r9   c                T    t        t        t        j                   f            sqt	        j
                         }t        j                   |       t        j                  |      t        j                  |      t	        j                  d|      nd fd}|S )z@Returns a decorator that calls the decorated function in a loop.r   )r   c                 t     t        j                  t        j                  z
         fdd        y )Nc                       | z  z         S r   r    )idx_bodyr:   r8   s     r   r   z)loop.<locals>.decorator.<locals>.<lambda>o   s    tEC$J./ r   )init_valr9   )lax	fori_looppl_utilscdiv)rA   r:   r8   r9   r;   zeros   `r   	decoratorzloop.<locals>.decoratork   s-    MMeemT*/r   )	allmapr%   is_concretejnpresult_typerC   convert_element_typearray)r:   r;   r8   r9   idx_typerH   rG   s   ````  @r   looprQ   Y   s     
S%%ud';<	=ueT2H$$UH5E$$UH5E##D(3D99Qh'DD  
r   jax_pallas_enable_debug_checksFzTIf set, ``pl.debug_check`` calls are checked at runtime. Otherwise, they are a noop.)defaulthelpc                  "    t         j                  S )z#Returns runtime checks are enabled.)_ENABLE_DEBUG_CHECKSvaluer    r   r   debug_checks_enabledrX      s    		#	##r   c                 .    t        j                  | |      S )zpCheck the condition if
  :func:`~jax.experimental.pallas.enable_debug_checks` is set, otherwise
  do nothing.
  )r   debug_check)r-   messages     r   rZ   rZ      s    
 
		i	11r   r    	out_shapemeshscratch_shapesnamec                      t        t        t        f       xrft        j                   fd       }|S )Nc                  6   t        j                  t        j                  |       t        j                  d 	      t	        j
                  fi dxs t        j                        i
fd       }t        j                  d       }r|d   S |S )Nc                     t        j                  t        j                  | j                  | j
                        t        | d      r-t        | j                  x}t         j                        s|      S d       S )Nr"   r!   )
r%   r+   rC   r   r   r   hasattrr1   r"   r'   )outmss     r   r   z/_make_kernel.<locals>.wrapper.<locals>.<lambda>   sb    H$$IIcii+ 3/"***BH,@,@ 

  

 r   r_   c                      t        j                  t        j                  g  gt	        t
              rndi t	        t              rS i S )Nr    )pl_primitives
run_scoped	functoolspartialr1   r   r   )arg_refsrA   out_refsr^   s   r   r@   z(_make_kernel.<locals>.wrapper.<locals>._   se    %%


D
78
7h
7'A>r )AN  HJ r   c                     | d   S )N.r    )refs    r   r   z/_make_kernel.<locals>.wrapper.<locals>.<lambda>   s
    #c( r   r   )r
   r   r%   r+   r#   core_mapr   fun_name)operandsr@   outsrk   rl   rA   r]   mesh_kwargsr_   r\   r^   
unwrap_outs      @@r   wrapperz_make_kernel.<locals>.wrapper   s    !!("2"2H=H!!
	
 	H  dLkL0Kd8KL M 2H=D 47*d*r   )r1   tuplelistr   jit)rA   r\   r]   r^   r_   rs   ru   rt   s   `````` @r   _make_kernelry      sG     ")eT];;;Z;I77+ + +8 
.r   )r^   compiler_params	interpretcost_estimatedebugr_   metadatarA   rz   r{   r|   r}   r~   c                   
 |t        d      t        |||||||||		      
t        | t        j                        r
fdS t        | fi 
S )a  Entry point for creating a Pallas kernel.

  This is a convenience wrapper around ``core_map`` for executing a kernel
  over a mesh and ``run_scoped`` for allocating scratch memory.

  If ``body`` is provided, this function behaves as a decorator:

  .. code-block:: python

    def kernel_body(in_ref, out_ref):
      ...
    kernel = pl.kernel(kernel_body, out_shape=...)

  If ``body`` is omitted, this function behaves as a decorator factory and
  will return a decorator that can be used to annotate a kernel body:

  .. code-block:: python

    @pl.kernel(out_shape=...)
    def kernel(in_ref, out_ref):
      ...

  Args:
    body: The body of the kernel. If provided, this function behaves as a
      decorator, and if omitted, this function behaves as a decorator factory.
    out_shape: The shape of the output. Should be a PyTree of
      ``jax.ShapeDtypeStruct`` or ``jax.Array`` s.
    mesh: The mesh to run the kernel on.
    scratch_shapes: The shapes of the scratch arrays.
    compiler_params: The compiler parameters to pass to the backend.
    interpret: Whether to run the function in interpret mode.
    debug: Whether or not to out helpful debugging information.
    cost_estimate: The cost estimate of the function.
    name: The (optional) name of the kernel.
    metadata: Optional dictionary of information about the kernel that will be
      serialized as JSON in the HLO. Can be used for debugging and analysis.

  Returns:
    If ``body`` is provided, returns a function that runs the kernel.
    It should take any number of input operands and returns an output with the
    same PyTree structure as `out_shape`.
    If ``body`` is omitted, returns a decorator that can be used to annotate
    a kernel body.
  zout_shape must be provided.)	r\   r]   r^   rz   r{   r|   r}   r_   r~   c                     t        | fi S r   )ry   )funkwdss    r   r   zkernel.<locals>.<lambda>  s    |C040 r   )r)   dictr1   r   NotSpecifiedry   )rA   r\   r]   r^   rz   r{   r|   r}   r_   r~   r   s             @r   kernelr      se    t 
2
33	#%!	
$ c&&'00%%%r   )r    N)6__doc__collections.abcr   r   r   ri   jax._srcr   r   r   r	   r%   r
   r   
jax_typingr   jax._src.lax_srcrC   jax._src.lax.control_flowr   jax._src.pallasr#   r   rg   r   rE   r   rL   
named_callr   objectr   Arrayr,   r2   	ArrayLiker6   intrQ   
bool_staterV   enable_debug_checksrX   rZ   MeshScratchShapeTreestrry   r   CompilerParamsCostEstimater   r   r    r   r   <module>r      s    7 7     %  )    2 + 7 - ! 	syy! K& K K"	Df 	D!1!1 	Dj***xD!"HRX$6674 "# $ 

	
 $J x))*D012D89< )v(($		  + $d $
2 =?$(	'"'||' ")!9!9' Tz	'T 0@s/?/?/A&*I& 79<@"8<"-1I&C,,, I&tmI& I& #33	I&
 $22T9I& I& "..5I& I& tI& #s(^d*I&r   