
    uki8F                    ~   U d Z ddlmZ ddlZddlmZ ddl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 ddlmZ ej$                  ZdZej(                  Zdd	d
Z ej.                  e      Zeeeeeee   eef   f   Z	 	 	 	 	 	 	 	 	 d.	 d/dZ ejB                  Z!ejD                  Z"	 d0	 	 	 d1dZ#	 d0	 	 	 	 	 d2dZ$d3dZ%d4dZ&d5dZ'd3dZ(d6dZ)	 	 	 d7	 	 	 	 	 	 	 d8dZ*d9dZ+ejX                  Z,ejZ                  Z-de-_         ej\                  Z.de._         ej^                  Z/de/_         ej`                  Z0ejb                  Z1ejd                  Z2ejf                  Z3ejh                  Z4ejj                  Z5ejl                  Z6ejn                  Z7ejp                  Z8ejr                  Z9ejt                  Z:ejv                  Z;ejx                  Z<ejz                  Z=ej|                  Z>ej~                  Z?ej                  Z@ej                  ZAej                  ZBej                  ZCd:dZDd:dZEeDe8_F        eEe8_G         G d dej                        ZI G d de      ZJi ZKdeLd<   i ZMd eLd!<    e
j                         ZOd"deIj                  f	 	 	 	 	 	 	 	 	 	 	 d;d#ZQ	 	 	 	 	 	 d<d$ZR G d% d&e      ZSi ZTd'eLd(<   i ZUd)eLd*<    e
j                         ZV	 d=	 	 	 	 	 	 	 d>d+ZW	 	 	 	 	 	 d?d,ZXej                  ZYej                  ZZej                  Z[ej                  Z\ej                  Z]ej                  Z^ej                  d@d-       Z`ej                  Zb ej                  ej                         ej                  Zeej                  Zfej                  Zgej                  Zhej                  Ziej                  Zjej                  Zkej                  Zlej                  Zmy)AzAn XLA client in Python.    )annotationsN)Mapping)AnyProtocolUnion)_jaxi  HostCUDA)cpugpuc	                    t        dt        j                         t        dt        j                         t        j
                  | ||||||||	      S )Nr   	asynchronousdistributed_clientnode_id	num_nodescollectivesnum_devices"get_local_topology_timeout_minutes#get_global_topology_timeout_minutestransfer_server_factory)register_custom_call_handler_xlaregister_custom_call_targetregister_custom_type_handlerregister_custom_typeget_tfrt_cpu_clientr   s	            L/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/jaxlib/xla_client.pymake_cpu_clientr   D   sR     ud&F&FGud&?&?@		!	!+)K*M5

 
    c           	     B    t        j                  d| t        di |      S ))Creates a PJRT C API TopologyDescription.tpu )r   get_default_c_api_topologydict)topology_namekwargss     r   #make_tfrt_tpu_c_api_device_topologyr)   b   s     
	(	(t~f~	NNr    c           	     B    t        j                  | |t        di |      S )r"   r$   )r   get_c_api_topologyr&   )c_apir'   r(   s      r   make_c_api_device_topologyr-   i   s     
	 	 t~f~	FFr    c                ,    t        j                  |       S N)r   pjrt_plugin_loadedplugin_names    r   r0   r0   p   s    		 	 	--r    c                2    t        j                  | |d       S )N)r,   r   load_pjrt_plugin)r2   library_paths     r   load_pjrt_plugin_dynamicallyr7   t   s    			{L	EEr    c                2    t        j                  | d |       y r/   r4   )r2   r,   s     r   load_pjrt_plugin_with_c_apir9   x   s    T51r    c                ,    t        j                  |       S r/   )r   pjrt_plugin_initializedr1   s    r   r;   r;   |   s    		%	%k	22r    c                .    t        j                  |        y)zInitializes a PJRT plugin.

  The plugin needs to be loaded first (through load_pjrt_plugin_dynamically or
  static linking) before this method is called.
  Args:
    plugin_name: the name of the PJRT plugin.
  N)r   initialize_pjrt_pluginr1   s    r   r=   r=      s     k*r    c                :    |i }t        j                  | |||      S )ax  Creates a PJRT C API client for a PJRT plugin.

  It is required that load_pjrt_plugin_dynamically is called once with the same
  plugin_name before this method is called.

  Args:
     plugin_name: the name of the PJRT plugin.
     options: extra platform-specific options.
     distributed_client: distributed client.

  Returns:
     A PJRT C API client for plugin_name.
  )r   get_c_api_client)r2   optionsr   r   s       r   make_c_api_clientrA      s-    & _G				
 r    c                 h   i } d| d<   t        j                  dd      j                         }t        j                  dd      }t        j                  dd      }|r|rt        d      |}t        j                  d	d      }t        j                  d
d      }|dvrt        d|z        || d<   |rt	        |      | d<   |r|dv| d<   |rt        |      dz  | d<   t        j                  dd      }t        t        |            | d<   t        j                  dd      }t        t        |            | d<   | S )zYGenerates the PjRt GPU plugin options.

  Returns:
    A dictionary of plugin options.
  cudaplatform_nameXLA_PYTHON_CLIENT_ALLOCATORdefaultXLA_CLIENT_MEM_FRACTION XLA_PYTHON_CLIENT_MEM_FRACTIONz{XLA_CLIENT_MEM_FRACTION is specified together with XLA_PYTHON_CLIENT_MEM_FRACTION. Remove the latter one, it is deprecated.XLA_PYTHON_CLIENT_PREALLOCATE(XLA_PYTHON_CLIENT_COLLECTIVE_MEM_SIZE_MB)rF   platformbfc
cuda_asynczcXLA_PYTHON_CLIENT_ALLOCATOR env var must be "default", "platform", "bfc", or "cuda_async", got "%s"	allocatormemory_fraction)falseFalse0preallocatei   collective_memory_size.XLA_PYTHON_CLIENT_ABORT_COLLECTIVES_ON_FAILURErS   abort_collectives_on_failure%XLA_PYTHON_CLIENT_USE_TFRT_GPU_CLIENTuse_tfrt_gpu_client)osgetenvlower
ValueErrorfloatintbool)r@   rO   rP   deprecated_memory_fractionrT   rU   abortuse_trft_gpu_clients           r    generate_pjrt_gpu_plugin_optionsrd      sV    '#'/ii5yAGGI)II7</!yy)I2N5  3o		92>+990" BB
	+-6	7  #'+!&!7G(0GGGM(+,B(Cw(OG$%
))Dc
J%,0U,<'
()		"I3O#',?(@#A'
 	.r    a  
A Shape is an object defined in C++ that duck types like the following class:

class Shape:
  '''Represents an XLA shape.

  A shape is either an array shape, having rank-many integer
  dimensions and an element type (represented by a Numpy dtype), or it
  is a tuple shape, having a shape for every tuple component:

    type shape =
        TupleShape of shape list
      | ArrayShape of { dimensions: int list; element_type: dtype }
  '''

  @staticmethod
  def tuple_shape(tuple_shapes) -> Shape:
    "Construct a tuple shape."

  @staticmethod
  def array_shape(element_type, dimensions, minor_to_major=None) -> Shape:

  @staticmethod
  def from_pyval(pyval) -> Shape:
    "Returns a Shape that describes a tuple-tree of Numpy arrays."

  def __init__(self, str) -> Shape:
    "Parses a shape string."
  def __eq__(self, other: Shape) -> bool:
  def __ne__(self, other: Shape) -> bool:
  def __hash__(self):
  def __repr__(self):
  def is_tuple(self) -> bool:
  def is_array(self) -> bool:
  def tuple_shapes(self) -> [Shape]:
  def numpy_dtype(self) -> np.dtype:
    "Like element_type(), but returns dtype('O') for a tuple shape."
  def xla_element_type(self) -> PrimitiveType:
  def element_type(self) -> np.dtype:
  def dimensions(self) -> (int, int, ...):
  def rank(self) -> int:
  def with_major_to_minor_layout_if_absent(self) -> Shape:
    "Returns a copy with missing layouts set to major-to-minor."

  def to_serialized_proto(self) -> bytes:
    "Returns 'shape' as a serialized proto."
z
A ProgramShape is a C++ object that duck types like the following class.

class ProgramShape:
  def __init__(self, parameter_shapes, result_shape):
  def parameter_shapes(self) -> [Shape]:
  def result_shape(self) -> Shape:
  def __repr__(self):
a  
A DeviceAssignment is a C++ object with the following signature.

def create(assignment):
  '''Builds a device assignment.

   Args:
     assignment: a 2D numpy array of device ordinal integers, indexed by
       [replica][computation_in_replica].
   Returns:
     A device assignment.
  '''

def replica_count():
  '''Returns the number of replicas.'''
def computation_count():
  '''Returns the number of computations per replica.'''
c                r    ~| j                  |      }|j                         D cg c]  }|d   	 c}S c c}w )Nr   )execute_sharded%disassemble_into_single_device_arraysself	argumentsdeviceresultsxs        r   LoadedExecutable_executern   X  s6      +'EEG	H1!A$	HH	Hs   4c                    ~| j                  |d      }|j                         D cg c]  }|d   	 c}|j                         j                  d      fS c c}w )NT)with_tokensr   )rf   rg   consume_token	get_tokenrh   s        r   #LoadedExecutable_execute_with_tokenrs   ^  sY       ='BBDEqtE''*
 Es   Ac                      e Zd ZdZdZy)CustomCallTargetTraitsr      N)__name__
__module____qualname__DEFAULTCOMMAND_BUFFER_COMPATIBLEr$   r    r   ru   ru   k  s    '  r    ru   c                  0    e Zd Z	 	 d	 	 	 	 	 	 	 	 	 	 	 ddZy)CustomCallHandlerc                    y r/   r$   )ri   namefnrL   api_versiontraitss         r   __call__zCustomCallHandler.__call__w  s     r    N)..)r   r_   r   ru   r   strr   r   rL   r   returnNonerw   rx   ry   r   r$   r    r   r}   r}   u  sI     '*	 	 %		 	 		 	r    r}   zdict[str, CustomCallHandler]_custom_callback_handlerz=dict[str, list[tuple[str, Any, int, CustomCallTargetTraits]]]_custom_callbackr   c                    t         j                  ||      }t        5  |t        v rt        |   | ||||       n)t        j                  |g       j                  | |||f       ddd       y# 1 sw Y   yxY w)a  Registers a custom call target.

  Args:
    name: bytes containing the name of the function.
    fn: a PyCapsule object containing the function pointer.
    platform: the target platform.
    api_version: the XLA FFI version to use. Supported versions are: 0 for the
      untyped FFI and 1 for the typed FFI.
    traits: custom call traits corresponding to XLA FFI handler traits.
  N)xla_platform_namesget_custom_callback_lockr   r   
setdefaultappend)r   r   rL   r   r   xla_platform_names         r   r   r     s|    & ),,Xx@ 4401
%{F !!"3R8??[&
)  s   AA++A4c           	     $   t         j                  | |       }t        5  |t        v r t        j                  d|       	 ddd       y|t        |<   |t        v r&t        |   D ]  \  }}}} ||||||        t        |= ddd       y# 1 sw Y   yxY w)a1  Registers a custom handler and use it to register existing custom calls.

  If a custom call handler for the platform already exist, calling this method
  is a no-op and it will not register a new handler.

  Args:
    platform: the target platform.
    handler: the function to register a custom call.
  zKCustom call handler for %s is already register. Will not register a new oneN)r   r   r   r   loggerdebugr   )rL   handlerr   r   r   r   r   s          r   r   r     s     ),,Xx@ .44ll

 . . 3:./,,+;<M+N B
'$Kb+[&AB
,
-. . .s    B7BBc                      e Zd ZddZy)CustomTypeIdHandlerc                    y r/   r$   )ri   	type_nametype_ids      r   r   zCustomTypeIdHandler.__call__  s    r    N)r   r   r   r   r   r   r   r$   r    r   r   r     s    r    r   zdict[str, CustomTypeIdHandler]_custom_type_id_handlerzdict[str, Any]_custom_type_idc                    t         j                  ||      }t        5  |t        v rt        |   | |       n't        j                  |g       j                  | |f       ddd       y# 1 sw Y   yxY w)zRegister a custom type id for use with the FFI.

  Args:
    type_name: a unique name for the type.
    type_id: a PyCapsule object containing a pointer to the ``ffi::TypeId``.
    platform: the target platform.
  N)r   r   _custom_type_id_lockr   r   r   r   )r   r   rL   r   s       r   r   r     sl     ),,Xx@ 33/0GD  !2B7>>g
	  s   A A&&A/c                   t         j                  | |       }t        5  |t        v r t        j                  d|       	 ddd       y|t        |<   |t        v r!t        |   D ]  \  }} |||        t        |= ddd       y# 1 sw Y   yxY w)a:  Register a custom type id handler and use it to register existing type ids.

  If a custom type id handler for the platform already exist, calling this
  method is a no-op and it will not register a new handler.

  Args:
    platform: the target platform.
    handler: the function to register a custom type id.
  zNCustom type id handler for %s is already register. Will not register a new oneN)r   r   r   r   r   r   r   )rL   r   r   r   capsules        r   r   r     s     ),,Xx@ -33ll

 - - 29-.O+*+<= -$g
+
,- - -s    B2BB
c              #     K   t        j                         }t        j                  |        	 d t        j                  |       y# t        j                  |       w xY ww)zVContext manager that overwrites and restores the current thread's execution_stream_id.N)r   get_execution_stream_idset_execution_stream_id)new_idsaveds     r   execution_stream_idr     sH      
&
&
(%v&(	  'D  's   *A!A A!AA!)	TNr   rv   NNNNN)r   Client)rH   )r'   r   r   DeviceTopology)r,   r   r'   r   r   r   )r2   r   r   r`   )r2   r   r6   r   r   r   )r2   r   r,   r   r   r   )r2   r   r   r   )NNN)r2   r   r@   z_NameValueMapping | Noner   z$_xla.DistributedRuntimeClient | Noner   z*_xla.TransferServerInterfaceFactory | None)r   _NameValueMappingr/   )r   r   r   r   rL   r   r   r_   r   ru   r   r   )rL   r   r   r}   r   r   )r   )r   r   r   r   rL   r   r   r   )rL   r   r   r   r   r   )r   r_   )n__doc__
__future__r   atexitcollections.abcr   
contextlibenumloggingrZ   	threadingtypingr   r   r   jaxlibr   r   ifrt_programs_versionifrt_version_number_ifrt_versionr   	getLoggerrw   r   r   r_   listr^   r`   r   r   r   get_topology_for_devicesr)   r-   r0   r7   r9   r;   r=   rA   rd   PrimitiveTypeShapeProgramShapeDeviceAssignmentDeviceCompileOptionsHostBufferSemanticsXlaComputationr   MemoryArray	ArrayImplLoadedExecutable
Executable
DeviceList
OpShardingHloShardingShardingNamedShardingSingleDeviceShardingPmapShardingGSPMDSharding
PjRtLayoutAutotuneCacheModern   rs   executeexecute_with_tokenIntFlagru   r}   r   __annotations__r   Lockr   rz   r   r   r   r   r   r   r   r    register_custom_call_partitioner encode_inspect_sharding_callbackhlo_sharding_util+register_custom_call_as_batch_partitionable	TracebackFramecontextmanagerr   JaxRuntimeErrorXlaRuntimeErrorregistercollect_garbagearray_result_handler+batched_copy_array_to_devices_with_shardingbatched_device_putreorder_shardsbatched_block_until_ready"check_and_canonicalize_memory_kindLayoutcustom_call_targetsArrayCopySemanticsr$   r    r   <module>r      s    "  #    	  ' '  ""  ((  
 
		8	$CsCcE4'G!HHI  '+(,  4 $$88  OOO &(GG"GG.F23+ )-?CJN	% = H	:)X ""

.`     ((   & 
$$.. 8 $$		

NN	(( __
__
__
==""00   ""__
** I 4  &I  # T\\    :< 6 ;     '	(  %;%C%C
  	
 # 
>..-.	.8(  ;= 7 <"$ $%y~~'    
	,--/-	-8 $(#H#H  #'#H#H  ** 44 ,
 NN	

 ( ( && $$ %00 44 , ,, $$ :: %)%L%L "	.. ,, r    