
    uki              	      
   U d Z ddlmZ ddlZddlmZ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ZddlZddlmZm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"  ejF                  e$      Z%de&d<   	 ddl'Z' ejX                  e-        e.       Z/de&d<   dZ0 ejb                  ddd      Z2 ejb                  d ejf                  dd      ji                         d      Z5 ejb                  d ejf                  dd      ji                         d      Z6 ejb                  d d!d"      Z7 ejb                  d#d!d$      Z8 ejr                  d%dd&'      Z: ejb                  d(dd)'      Z; ejx                  d*d+d,'      Z= ejb                  d-dd.'      Z> ejb                  d/dd0'      Z? ejr                  d1dd2      Z@ ejr                  d3dd4      ZAd5 ZBd6aCeeDeeDeEeFeE   eGeHf   f   ZI	 	 dd7ZJ	 d	 	 	 dd8ZKdd:ZLeg ee j                  df   f   ZNed;ee j                  df   f   ZPej                   G d< d=             ZRi ZSd>e&d?<   daTd9e&d@<   i aUdAe&dB<   i aVdCe&dD<    ej                         ZXd6aYdEe&dF<    ej                         ZZi Z[dGe&dH<   g Z\dIe&dJ<    ej                         Z]dKdLhZ^de&dM<   dNhZ_de&dO<   dd+d6dddP	 	 	 	 	 	 	 	 	 	 	 ddQZ`	 d	 	 	 ddRZa e`dSeadd6T       ddUZb e`dV e	eLdWX      dYd+T       	 	 	 	 ddZZc	 	 	 	 dd[Zddd\Zed] ZfeeDeDeEz  eFeE   z  eGz  eHz  f   Zg	 d	 	 	 	 	 dd^Zhd_dddddd`	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddaZiddbZjdc ZkdddddeZli Zmdfe&dg<   elj                         D ]&  \  ZoZpemj                  epg       j                  eo       ( ddhZsddiZtddjZuddkZvdl ZwddmZxdn ZyddoZzdp Z{ddqZ|ddrZ}	 d	 	 	 ddsZ~ ej                  dd6t      	 d	 	 	 ddu       Z	 d	 	 	 ddvZ	 d	 	 	 ddwZ	 d	 	 	 ddxZ	 d	 	 	 ddyZddzZddd{Zddd|Zddd}Z ej                  dd6t      	 	 	 d	 	 	 	 	 dd~       Z	 d	 	 	 ddZdddZ ej                  dd6t      	 d	 	 	 dd       ZdddZ	 d	 	 	 ddZ	 d	 	 	 ddZddZdddZddZd Z ej(                  ddd e	ed            Z ej(                  ddd e	ed            Z ej(                  ddd e	ed            Zy# e($ r dZ'Y e)$ rZ*e%jW                  de*       dZ'Y dZ*[*dZ*[*ww xY w)a  Interface and utility functions to XLA.

This module wraps the XLA client(s) and builders to standardize their interfaces
and provide some automatic type mapping logic for converting between Numpy and
XLA. There are also a handful of related casting utilities.
    )annotationsN)CallableMapping)partial)AnyUnion)Sequence)config)distributed)hardware_utils)traceback_util)util)get_tpu_library_path)
xla_client)_jax)	_profiler
Any | Nonejax_pluginsz Failed to import jax_plugins: %sset[str]'FORCE_FORWARD_COMPAT_LOWERING_PLATFORMS4   jax_xla_backend z/Deprecated, please use --jax_platforms instead.)helpjax_backend_targetJAX_BACKEND_TARGETzFEither "local" or "rpc:address" to connect to a remote service target.jax_platform_nameJAX_PLATFORM_NAMEjax_cuda_visible_devicesallzrRestricts the set of CUDA devices that JAX will use. Either "all", or a comma-separate list of integer device IDs.jax_rocm_visible_deviceszrRestricts the set of ROCM devices that JAX will use. Either "all", or a comma-separate list of integer device IDs.mock_num_gpu_processeszIMock number of JAX processes in GPU client. Value zero turns off mocking.)namedefaultr   jax_mock_gpu_topologyzMock multi-host GPU topology in GPU client. The value should be of the form "<number-of-slices> x <number-of-hosts-per-slice> x <number-of-devices-per-host>". Empty string turns off mocking.jax_cpu_enable_async_dispatchTzcOnly applies to non-parallel computations. If False, run computationsinline without async dispatch.&jax_cross_host_transfer_socket_addresszSocket address to use for cross host device transfers via DCN. Necessary only if the PjRt plugin does not support cross host transfers."jax_cross_host_transport_addresseszComma-separated list of transport addresses to use for cross host device transfers via DCN. If not set, defaults to [0.0.0.0:0] * 4.'jax_cross_host_transfer_timeout_secondszZTimeout for cross host transfer metadata exchange through KV store. Default is one minute.%jax_cross_host_transfer_transfer_sizez)Chunk size for chunked transfer requests.c                 <    t        j                  dt        d       y )Nzos.fork() was called. os.fork() is incompatible with multithreaded code, and JAX is multithreaded, so this will likely lead to a deadlock.   )
stacklevel)warningswarnRuntimeWarning     N/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/jax/_src/xla_bridge.py_at_forkr4      s    
--Hq"r2   Fc                    t         j                  rt        t        d      syg } t        j                  rt        j                  j                  d      } t        j                  j                  t         j                  | d}t        j                  t        j                  |d<   t        j                  t        j                  |d<   t        j                  di |S )z,Creates a transfer server interface factory.&make_transfer_server_interface_factoryN,)distributed_clientsocket_addresstransport_addresses#cross_host_transfer_timeout_secondstransfer_sizer1   )"CROSS_HOST_TRANSFER_SOCKET_ADDRESSvaluehasattrr   CROSS_HOST_TRANSPORT_ADDRESSESsplitr   global_stateclient#CROSS_HOST_TRANSFER_TIMEOUT_SECONDS!CROSS_HOST_TRANSFER_TRANSFER_SIZEr6   )r:   transfer_server_kwargss     r3   _make_transfer_server_factoryrG      s     -
2
2d<=#))8>>DDSI'44;;:@@0
 )..:+11 @A&,,8)// ?+		4	4	N7M	NNr2   c                   t        j                  d      sFt        j                  d| xs d      }t	        j
                  |       t        j                  d      sJ t        j                  d      st        j                  d       |i }t        j                  d|t        j                  j                  t                     S )zEReturns a TPU client. Defaults to allowing 32 in-flight computations.tpuz	libtpu.so)r   pjrt_plugin_loadedr   load_pjrt_plugin_dynamicallyr   register_plugin_profilerpjrt_plugin_initializedinitialize_pjrt_pluginget_c_api_clientr   rB   rC   rG   )library_pathoptionsc_apis      r3   make_tpu_clientrS      s     
	 	 	'33|*{E &&u-""5)))		%	%e	,&_G			%%#%	
 r2   xla_client.Client | Nonec                      fd}t        j                   |      }|j                          	 t        t	               t        d            }|j                          |S # |j                          w xY w)Nc                 8    t        j                  d  d       y )Nz/TPU backend initialization is taking more than z} seconds. Did you run your code on all TPU hosts? See https://docs.jax.dev/en/latest/multi_process.html for more information.)r.   r/   
timer_secss   r3   _log_warningz/tpu_client_timer_callback.<locals>._log_warning   s!    MM7
| D r2   rI   )	threadingTimerstartrS   r   _options_from_jax_configscancel)rX   rY   trC   s   `   r3   tpu_client_timer_callbackr`      s]     ooj,/!'')!%(*F HHJ	- HHJs   A A/.c                  L    e Zd ZU ded<   ded<   dZded<   dZded<   d	Zd
ed<   y	)BackendRegistrationBackendFactoryfactoryintpriorityFboolfail_quietlyexperimentalNr   rR   )__name__
__module____qualname____annotations__rh   ri   rR   r1   r2   r3   rb   rb      s3     -
 , , %r2   rb   zdict[str, BackendRegistration]_backend_factories_default_backenddict[str, xla_client.Client]	_backendsdict[str, str]_backend_errorsrg   _plugins_registeredzdict[str, TopologyFactory]_topology_factoriesz	list[Any]_plugin_callbackscudarocm_nonexperimental_pluginsMETAL_experimental_pluginsrf   rh   ri   make_topologyrR   c                   t         5  | t        v rt        d|  d      	 d d d        t        |||||      t        | <   |
|t
        | <   y y # 1 sw Y   ,xY w)NzBackend z already initialized)_backend_lockrq   RuntimeErrorrb   rn   ru   )r#   rd   rf   rh   ri   r}   rR   s          r3   register_backend_factoryr     su      @y8D6)=>?? @ 1X|\5:T - @ @s   AAc                   | t         j                  j                  t        j                  j
                  }|dk(  r9t        j                  j                  t         j                  j                        } nW|dk(  rNt        j                  j                         } | j                          t        j                  | j                         n|J t        j
                  dk\  rt        j
                  nd}t        j                  t         j
                  t         j                  j                  t         j                  j"                  t         j                  j$                  | |t&        j
                  t(        j
                  t+               	      S )a  Creates a CPU client with the requested collectives implementation.

  The implementation of CPU collectives used by the client is determined by the
  flag `--jax_cpu_collectives_implementation` - unless `collectives` is
  provided, in which case the flag is overridden and `collectives` is used.

  Args:
    collectives: An optional CPU collectives implementation, used by the client
      if provided.

  Raises:
    RuntimeError: If `--jax_cpu_collectives_implementation` is unknown.

  Returns:
    The created CPU client.
  Ngloo)r8   mpir   )	asynchronousr8   node_id	num_nodescollectivesnum_devices"get_local_topology_timeout_minutes#get_global_topology_timeout_minutestransfer_server_factory)r   rB   rC   r
   cpu_collectives_implementationr>   r   _xlamake_gloo_tcp_collectivesmake_mpi_collectivesInitatexitregisterFinalizenum_cpu_devicesmake_cpu_client_CPU_ENABLE_ASYNC_DISPATCH
process_idnum_processes&cpu_get_local_topology_timeout_minutes'cpu_get_global_topology_timeout_minutesrG   )r   collectives_implr   s      r3   r   r   $  s&   * [55<<H<<BB6!OO==&33:: > k 
U	"OO88:kook**+ %%%)8)>)>!)C%%+		#	#-33$1188&&11((66)O)U)U*Q*W*W;=

 
r2   cpu)rf   rh   c                    	 | j                  dd      \  }}}t        |      t        |      z  S # t        t        f$ r t        d      w xY w)Nxr,   ztMock topology must be of the form "<number-of-slices> x <number-of-hosts-per-slice> x <number-of-devices-per-host>".)rA   re   
IndexError
ValueError)topology
slices_strhosts_per_slice_str_s       r3   get_num_nodes_from_gpu_topologyr   Y  sZ    9+3>>#q+A(j%q_s#6777
# 9 8 9 99s	   ,/ A
rI   g      N@rW   i,  c                    | si S i }| j                  d      D ]4  }	 |j                  t        j                  j                        \  }}|||<   6 |S # t        $ r t
        j                  d||        Y [w xY w)a@  Gets the names and library paths of PJRT plugins to load from env var.

  Args:
    plugins_from_env: plugin name and paths from env var. It is in the format
      of 'name1:path1,name2:path2' ('name1;path1,name2;path2' for windows).

  Returns:
    A dict of {plugin_name: library path} for the PJRT plugins to load.
  r7   z;invalid value %s in env var PJRT_NAMES_AND_LIBRARY_PATHS %s)rA   ospathpathsepr   loggerwarning)plugins_from_envpjrt_pluginspluginr#   rP   s        r3   (_get_pjrt_plugin_names_and_library_pathsr   i  s     
I, &&s+ 	f!<<8dL'l4	 
  nn
G

s   1A A43A4c                    t        |       5 }t        j                  |      }ddd       d j                         vrt	        d      |d    |j
                  d      fS # 1 sw Y   >xY w)aq  Gets PJRT plugin configuration from a json file.

  The json file needs to have a "library_path" field for the plugin library
  path. It can have an optional "create_option" field for the options used when
  creating a PJRT plugin client. The value of "create_option" is key-value
  pairs. Please see xla_client._NameValueMapping for the supported types of
  values.
  NrP   z<PJRT plugin config file should contain "library_path" field.create_options)openjsonloadkeysr   get)	json_pathfr
   s      r3   _get_pjrt_plugin_configr     sm     I !YYq\F;6;;=(
F  
 *&**-=">	?? s   AA(c                    t               } t        rft        j                  t        j                  t        j
                  dz         D ]-  \  }}}t        j                  d|       | j                  |       / nt        j                  d       ddl	m
}  |d      D ]=  }t        j                  d|j                         | j                  |j                         ? | D ]D  }t        j                  d	|       d
}	 t        j                  |      }|s4	 |j%                          F y
# t        $ r t        j                  d|       Y 8t         $ r t        j#                  d       Y Ww xY w#  t        j#                  d|       Y xY w)a2  Discovers plugins in the namespace package `jax_plugins` and import them.

  There are two methods used to discover plugin modules. They are intended
  to be used together by implementers in order to cover all packaging and
  development cases:

  1. Define a globally unique module under the `jax_plugins` namespace
     package (i.e. just create a `jax_plugins` directory and define your
     module below it).
  2. If building a package via pyproject.toml or setup.py, advertise your
     plugin module name by including an entry-point under the `jax_plugins`
     group which points to your full module name.

  During Jax startup, Jax will load each module discovered in such a way and
  call its `initialize()` function. It is expected that this function should
  register its concrete plugin name/implementations via call(s) to
  `jax._src.xla_bridge.register_plugin(name, priority=, library_paty=,
  options=)`. Since `initialize()` functions are called for all installed
  plugins, they should avoid doing expensive, non-registration related work.

  TODO: We should provide a variant of `register_plugin` which allows the
  library_path and options to be resolved via a callback. This would enable
  light-weight plugin registration in cases where options need to be derived
  from heavy-weight system initialization.
  .z$Discovered path based JAX plugin: %sz+No jax_plugins namespace packages availabler   )entry_pointsr   )groupz+Discovered entry-point based JAX plugin: %szLoading plugin module %sNz?Jax plugin configuration error: Plugin module %s does not existzDJax plugin configuration error: Plugin module %s could not be loadedzFJax plugin configuration error: Exception when calling %s.initialize())setr   pkgutiliter_modules__path__rj   r   debugaddimportlib.metadatar   r>   	importlibimport_moduleModuleNotFoundErrorr   ImportError	exception
initialize)plugin_modulesr   r#   r   entry_pointplugin_module_nameplugin_modules          r3   discover_pjrt_pluginsr     sm   4 5. **k22S8 
4 ll94@	 LL>? .!6 *k
LL>""${(()* + H
LL+-?@M.--.@Am H  "H
  ;nn &'9; . - ..H 34F	Hs$   9D%E)%E&E&%E&)Fc                   i }t         j                  j                  }t        |t              rVg }|r|j                  d      }|D ];  }|j                  d      }t        |      dk7  rt        d| d      |d   ||d   <   = n!t        |t              r|j                  |       | dv r| d	k(  rt        j                  nt        j                  }|d
k7  r+|j                  d      D cg c]  }t        |       c}|d<   t        j                  xs d }|rt        |      nt        j                  }	|	dkD  |d<   |	dkD  r|	|d<   |r||d<   |S c c}w )N;:r,   zGMultiple ':' separators for option in jax_pjrt_client_create_options: 'z"'. Should be in format 'key:value'   r   rw   rx   rw   r    r7   visible_devicesenable_mock_ncclr   mock_gpu_topology)r
   jax_pjrt_client_create_optionsr>   
isinstancestrrA   lenr   dictupdateCUDA_VISIBLE_DEVICES_ROCM_VISIBLE_DEVICESre   MOCK_GPU_TOPOLOGYr   MOCK_NUM_GPU_PROCESSES)
plugin_namerQ   pjrt_client_optionspjrt_client_option_listoptionoption_listr   r   r   mock_num_processess
             r3   r]   r]     st   '==CC#S)  3 9 9# >) /LL%k
k
a
006x 8../ 	/ !,Agk!n/ %t,NN&'$$5@F5J+11"(( %4C4I4I#4N#OqCF#Og )//74 ::KL5;; "4q"8GA/gk	'8#$	. $Ps   %E	c                |   t        j                  |       st        j                  |        i }|#|j                  t	        |      r |       n|       |j                  t        |              t        j                  j                  t        j                  | |d      S t        j                  j                  t        j                  j                  d}t        j                  j                  x}||d<   ||j                  |       t        j                  | |t        j                  j                  t                     S )a<  Creates a PjRt client for the given plugin.

  Args:
    plugin_name: the name of the plugin.
    options: Optional. It is used when creating a PJRT plugin client. Can be a
      callable, in which case it will be invoked upon plugin initialization
      time, and will be expected to return an option dictionary.
  N)r   r   partition_index)r   rM   rN   r   callabler]   r   rB   rC   make_c_api_clientr   r   r   rG   )r   rQ   updated_optionsdistribute_optionsr   s        r3   make_pjrt_c_api_clientr     s    
	+	+K	8%%k2$&/(979wG2;?@$$,''_dKK ))44++99 %11AAAoN,;()o.		%	%%%#%	
 r2   i  )rf   rP   rQ   rR   rd   r}   c          	        |r|rt         j                  d|        y|s|st         j                  d|        y||t        d      |t        t        | |      }t         j                  d| |       |,t        j                  | |      }t        j                  |       n|J t        j                  | |       |xs t        t        j                  |      }| t        v}t        | ||d|||       |S )	a   Registers a backend factory for the PJRT plugin.

  Args:
    plugin_name: the name of the plugin.
    priority: the priority this plugin should be registered in jax backends.
      Default to be 400.
    library_path: Optional. The full path to the .so file of the plugin. The
      plugin needs to provide either the library_path or the c_api.
    options: Optional. It is used when creating a PJRT plugin client. Can be a
      callable, in which case it will be invoked upon plugin initialization
      time, and will be expected to return an option dictionary.
    c_api: Optional. The plugin can provide a PJRT C API to be registered.
    factory: Optional. A factory function that creates a PJRT client. If not
      provided, a default factory will be used.
  zHBoth library_path and c_api are provided when registering PJRT plugin %sNzGNeither library_path nor c_api provided when registering PJRT plugin %szCannot provide both 'factory' and 'options' when registering PJRT plugin. When providing a custom factory, the factory's must handle its own options.)rQ   "registering PJRT plugin %s from %sFr|   )r   errorr   r   r   r   r   rK   r   rL   load_pjrt_plugin_with_c_apimake_c_api_device_topologyry   r   )r   rf   rP   rQ   rR   rd   r}   ri   s           r3   register_pluginr   +  s   4 e
LL	
 	e
LL	
 W0
	 
 _,k7KG,,*K 33KNE&&u-**;>X7:+P+PRW#X-$<<,;((-L)6eE 
,r2   c                    t        t        j                  dd            } | j                         D ]N  \  }}|j	                  d      rt        |      \  }}n|}d}t        j                  d||       t        |||       P y)a  Registers backend factories for PJRT plugins.

  A backend factory will be registered for every PJRT plugin in the input
  string, in the format of 'name1:path1,name2:path2' ('name1;path1,name2;path2'
  for windows). The path can be a path to the plugin library or a path to the
  plugin configuration json file. The json file needs to have a "library_path"
  field for the plugin library path. It can have an optional "create_option"
  field for the options used when creating a PJRT plugin client. The value of
  "create_option" is key-value pairs. Please see xla_client._NameValueMapping
  for the supported types of values.

  TPU PJRT plugin will be loaded and registered separately in make_tpu_client.
  PJRT_NAMES_AND_LIBRARY_PATHSr   z.jsonNr   )rP   rQ   )	r   r   getenvitemsendswithr   r   r   r   )r   r   r   rP   rQ   s        r3   'register_pjrt_plugin_factories_from_envr   o  s     :ii.3, (--/ 	Mk4}}W5d;lGlg
LL,k< KlGL	Mr2   c                 2   t         5  t        sjt                t                t        5  t
        j                         D ]-  } | j                  t        D ]  } || j                          / 	 d d d        dad d d        y # 1 sw Y   xY w# 1 sw Y   y xY w)NrR   T)	_plugin_lockrt   r   r   _plugin_callback_lockrn   valuesrR   rv   )rd   callbacks     r3   #_discover_and_register_pjrt_pluginsr    s    
  !  ./  ,)002 	,G]]&- ,W]]+,	,,
 !! !, ,! !s(   !B$B B.
BB
	BBgpur   zdict[str, list[str]]_alias_to_platformsc                     t               } | t        t              z  } | t        t              z  } | t        t        j	                               z  } | t        t
        j                               z  } | S N)r   ry   r{   rn   r   _platform_aliasesr   )	platformss    r3   known_platformsr	    sa    e)s+,,)s()))s%**,--)s$++-..)	r2   c                    | t               v S r  )r	  platforms    r3   is_known_platformr    s     
_&	&&r2   c                    t         j                  | d      }|| S t               }|D ]  }||j                         v s|c S  t	        d|  d|  ddj                  |j                               z         )a=  Replaces platform aliases with their concrete equivalent.

  In particular, replaces "gpu" with either "cuda" or "rocm", depending on which
  hardware is actually present. We want to distinguish "cuda" and "rocm" for
  purposes such as MLIR lowering rules, but in many cases we don't want to
  force users to care.
  NzUnknown backend: 'z4' requested, but no platforms that are instances of z% are present. Platforms present are: r7   )r  r   backendsr   r   join)r  r  bps       r3   canonicalize_platformr    s     "%%h5)Oj! aAFFH}h 	)( 488@z B//14!&&(1CD 	E Er2   c                0    t         j                  | | g      S )zExpands, e.g., "gpu" to ["cuda", "rocm"].

  This is used for convenience reasons: we expect cuda and rocm to act similarly
  in many respects since they share most of the same code.
  )r  r   r  s    r3   expand_platform_aliasr    s     
	 	 H:	66r2   c                
    | dv S )Nr   r1   r  s    r3   is_gpur    s    	%	%%r2   c                 ^    t         5  t        t              dk7  cddd       S # 1 sw Y   yxY w)z7Returns true if backends have already been initialized.r   N)r   r   rq   r1   r2   r3   backends_are_initializedr    s&     y>Q  s   #,c                    t         5  t        r:t        j                         D ]"  }|j                   | |j                         $ nt
        j                  |        ddd       y# 1 sw Y   yxY w)a  Registers a callback to be called with c_api after plugins discovery.

  The callback will be called on all discovered PJRT C API plugins. If
  `register_plugin_callbacks` is called before the plugins are discovered, the
  callback will be called right after the plugins are discovered. Otherwise, the
  callback will be called immediately when `register_plugin_callbacks` is
  called.

  Args:
    callback: the callback to be called with c_api.
  Nr   )r   rt   rn   r   rR   rv   append)r  rd   s     r3   register_plugin_callbacksr    s]      )'..0 ('==$

'( x() ) )s   *A&+A&&A/c                 h   t                t        5  t        rt        cd d d        S t        s,t	        t
        d      rt        j                  t               dat        j                  j                  x} rng }| j                  d      D ]  }|j                  t        |              t        t        |      dd      }dgt        |      z  }t!        t#        |||            }n=t$        j'                         D cg c]  \  }}||j(                  |j*                  f  }}}d}|D ]>  \  }}}		 |d	k(  rt-        j.                         s"t1        |      }
|
t        |<   ||kD  r|
a|}@ t2        J t        j                  j                  s
tA                t        cd d d        S c c}}w # t4        $ rv}d
| d| }|	r(t7        |      t8        |<   t:        j=                  |       n:t        j                  j                  r|dz  }t?        |      |dz  }t?        |      Y d }~d }~ww xY w# 1 sw Y   y xY w)Nregister_at_fork)beforeTr7   r   Firw   zUnable to initialize backend 'z': zD (set JAX_PLATFORMS='' to automatically choose an available backend)zg (you may need to uninstall the failing plugin package, or set JAX_PLATFORMS=cpu to skip this backend.))!r  r   rq   _at_fork_handler_installedr?   r   r  r4   r
   jax_platformsr>   rA   extendr  ranger   listziprn   r   rf   rh   r   has_visible_nvidia_gpu_init_backendro   	Exceptionr   rs   r   infor   _suggest_missing_backends)r"  r  r  
prioritiesfail_quietly_listplatform_registrationsregistrationdefault_priorityrf   rh   backenderrerr_msgs                r3   r  r    s<    &' 55 5
 &'"6H*I*#' ,,222}2i#))#. :(.x89:YB/j !'C	N2#Iz#45 7  %%' $h \**L,E,E
F   
 ,B &((L&vn&K&K&M
)%	(&&$
%
&. '''%%!k5 5* "  
&28*CuE&)#h/(
#
++g
!!'']]G W%
%   A  AGW%
% 	
&M5 5sZ   H(CH(:#F H(,F&H(F&#3H( H(&	H%/A,H H( H%%H((H1c                    t        j                         dk7  ry t        J t        j                  } dt        vryt        j                         ret        t        d      r;dt        v r3t        d   }d| d}d|v r|dz  }|dz  }t        j                  |       y t        j                  d	|  d       y d
t        vr5t        j                         d   dkD  rt        j                  d|  d       y y y )NLinuxrw   GpuAllocatorConfigz#CUDA backend failed to initialize: r   z-no supported devices found for platform CUDA.zThis may be due to JAX pre-allocating too much device memory, leaving too little for CUDA library initialization. See https://docs.jax.dev/en/latest/gpu_memory_allocation.html for more details and potential workarounds.z5(Set TF_CPP_MIN_LOG_LEVEL=0 and rerun for more info.)zjAn NVIDIA GPU may be present on this machine, but a CUDA-enabled jaxlib is not installed. Falling back to rI   r   zyA Google TPU may be present on this machine, but either a TPU-enabled jaxlib or libtpu is not installed. Falling back to )py_platformsystemro   r  rq   r   r'  r?   r   rs   r   r   %num_available_tpu_chips_and_device_id)default_platformr2  warning_msgs      r3   r+  r+  =  s   W$ 		%%	%%..9!F!F!Ht)*v/HF#c9#a@k	8C	?8	
 LLknn[!nn N(), - I."V"V"XYZ"[^_"_
NN /03 4 #`r2   c                 p    t         j                  d       t        5  i ai ad ad d d        y # 1 sw Y   y xY w)NzClearing JAX backend caches.)r   r   r   rq   rs   ro   r1   r2   r3   _clear_backendsr=  ]  s9    
 	,,-. IO  s   ,5c           	        t         j                  | d       }|-t        d|  dt        t         j	                                d      |j
                  rt        j                  d|  d       t        j                  d|        |j                         }|t        d|  d      |j                         d	k(  r+t        |j                               d	k(  rt        d|  d
      t        j                  d|j                  fd|j!                         fd|j                         fd|j#                         f       t        j                  d|        |S )N	Backend 'z(' is not in the list of known backends: r   z
Platform 'zK' is experimental and not all JAX functionality may be correctly supported!zInitializing backend '%s'zCould not initialize backend ''r   z' provides no devices.zInitialized backendprocess_indexdevice_countlocal_deviceszBackend '%s' initialized)rn   r   r   r%  r   ri   r   r   r   rd   rB  r   _get_all_devicesr   distributed_debug_logr  rA  rC  )r  r/  r1  s      r3   r(  r(  i  sQ   #''$7,

H:E"'')*
+1	./ / 
NNZz *? ? @,,*H5  "' _
7zC
DD q S)A)A)C%D%I
8*,BC
DD3W5E5EF-w/D/D/FG,g.B.B.DE-w/D/D/FGI 	,,)84	.r2   c           
        | t        | t              s| S | xs& t        j                  xs t        j                  xs d } t               }| gt        |       } |j                  | d       }|F| t        v r$t        d|  dt        |     dt        |             t        d|  dt        |             |S t        J t        S )Nr?  z' failed to initialize: z. Available backends are zUnknown backend )r   r   _XLA_BACKENDr>   _PLATFORM_NAMEr  r  r   rs   r   r%  ro   )r  bsr1  s      r3   _get_backend_uncachedrJ    s    
 *Xs";OL,,,L0D0DL(z"$X.HffXt$G	_	$Yxj0H-h78 9559"XJ@ A 	A XJ&?Rz
JL LN'''r2   )max_sizetrace_context_in_keyc                    t        |       S r  )rJ  r  s    r3   get_backendrN    s     
x	((r2   c                2    | | j                   S t               S )zEReturns the Backend associated with `device`, or the default Backend.)rC   rN  )devices    r3   get_device_backendrQ    s     ==	r2   c                F    t        t        |       j                               S )a  Returns the total number of devices.

  On most platforms, this is the same as :py:func:`jax.local_device_count`.
  However, on multi-process platforms where different devices are associated
  with different processes, this will return the total number of devices across
  all processes.

  Args:
    backend: This is an experimental feature and the API is likely to change.
      Optional, a string representing the xla backend: ``'cpu'``, ``'gpu'``, or
      ``'tpu'``.

  Returns:
    Number of devices.

  )re   rN  rB  r1  s    r3   rB  rB    s    & 
[!..0	11r2   c                F    t        t        |       j                               S )z:Returns the number of devices addressable by this process.)re   rN  local_device_countrS  s    r3   rU  rU    s     
[!446	77r2   c                4    t        |       j                         S )a(  Returns a list of all devices for a given backend.

  .. currentmodule:: jaxlib._jax

  Each device is represented by a subclass of :class:`Device` (e.g.
  :class:`CpuDevice`, :class:`GpuDevice`). The length of the returned list is
  equal to ``device_count(backend)``. Local devices can be identified by
  comparing :attr:`Device.process_index` to the value returned by
  :py:func:`jax.process_index`.

  If ``backend`` is ``None``, returns all the devices from the default backend.
  The default backend is generally ``'gpu'`` or ``'tpu'`` if available,
  otherwise ``'cpu'``.

  Args:
    backend: This is an experimental feature and the API is likely to change.
      Optional, a string representing the xla backend: ``'cpu'``, ``'gpu'``, or
      ``'tpu'``.

  Returns:
    List of Device subclasses.
  )rN  devicesrS  s    r3   rW  rW    s    2 
W		%	%	''r2   c                 ,    t        d      j                  S )z5Returns the platform name of the default XLA backend.N)rN  r  r1   r2   r3   default_backendrY    s    	T		#	##r2   c                z    t        |       }t        |d      r$t        |d      r|j                  |j                  fS y)ziReturns the PJRT C API version of the backend.

  Returns None if the backend does not use PJRT C API.
  pjrt_c_api_major_versionpjrt_c_api_minor_versionN)rN  r?   r[  r\  r  r1  s     r3   backend_pjrt_c_api_versionr^    sB    
 !'W01g)7 ,,g.N.NOO	r2   c                2    t        |       }t        |dd      S )a*  Returns the XLA version of the backend.

  Returns None if the backend does not use PJRT C API or does not have
  xla_version in the plugin attributes. This method can be used to skip features
  that are not available before certain xla_version if the backend is a
  plugin and uses xla_version.
  xla_versionNrN  getattrr]  s     r3   backend_xla_versionrc    s     !'	-	..r2   c                2    t        |       }t        |dd      S )aZ  Returns the StableHLO version of the backend.

  Returns None if the backend does not use PJRT C API or does not have
  stablehlo_current_version in the plugin attributes. This method can be used to
  skip features that are not available before certain stablehlo_current_version
  if the backend is a plugin and uses stablehlo_current_version.
  stablehlo_current_versionNra  r]  s     r3   backend_stablehlo_versionrf    s     !'	5t	<<r2   c                   |t        j                  d       |} | t        |      j                         } d| cxk  rt	        |      k  sn t        d|        t        |      D cg c]  }|j                  | k(  s| c}S c c}w )a  Like :py:func:`jax.devices`, but only returns devices local to a given process.

  If ``process_index`` is ``None``, returns devices local to this process.

  Args:
    process_index: the integer index of the process. Process indices can be
      retrieved via ``len(jax.process_count())``.
    backend: This is an experimental feature and the API is likely to change.
      Optional, a string representing the xla backend: ``'cpu'``, ``'gpu'``, or
      ``'tpu'``.

  Returns:
    List of Device subclasses.
  zThe argument to jax.local_devices has been renamed from `host_id` to `process_index`. This alias will eventually be removed; please update your code.r   zUnknown process_index )r.   r/   rN  rA  process_countr   rW  )rA  r1  host_idds       r3   rC  rC    s    $ MM	 M(668M
}
5}W5
5
-m_=
>>W%	JM)I!	JJ	Js   &B;Bc                4    t        |       j                         S )au  Returns the integer process index of this process.

  On most platforms, this will always be 0. This will vary on multi-process
  platforms though.

  Args:
    backend: This is an experimental feature and the API is likely to change.
      Optional, a string representing the xla backend: ``'cpu'``, ``'gpu'``, or
      ``'tpu'``.

  Returns:
    Integer process index.
  )rN  rA  rS  s    r3   rA  rA  0  s      
W		+	+	--r2   c                B    t        j                  d       t        |       S )Nzrjax.host_id has been renamed to jax.process_index. This alias will eventually be removed; please update your code.)r.   r/   rA  rS  s    r3   ri  ri  D       
--=> 
w	r2   c                F    d t        |       D        }t        |d      dz   S )z@Returns the number of JAX processes associated with the backend.c              3  4   K   | ]  }|j                     y wr  )rA  ).0rj  s     r3   	<genexpr>z process_count.<locals>.<genexpr>P  s     3Q3s   r   )r$   r   )rW  max)r1  gens     r3   rh  rh  K  s%    
 	4''"23#	S!	q	  r2   c                B    t        j                  d       t        |       S )Nzujax.host_count has been renamed to jax.process_count. This alias will eventually be removed; please update your code.)r.   r/   rh  rS  s    r3   
host_countru  U  rm  r2   c                <    t        t        t        |                   S )a4  Returns the list of all JAX process indices associated with the backend.

  Args:
    backend: This is an experimental feature and the API is likely to change.
      Optional, a string representing the xla backend: ``'cpu'``, ``'gpu'``, or
      ``'tpu'``.

  Returns:
    List of integer process indices.
  )r%  r$  rh  rS  s    r3   process_indicesrw  \  s     
eM'*+	,,r2   c                B    t        j                  d       t        |       S )Nzujax.host_ids has been renamed to jax.process_indices. This alias will eventually be removed; please update your code.)r.   r/   rw  rS  s    r3   host_idsry  m  s"     --=> 
	!!r2   c                0    dt        |       j                  v S )Nz
PJRT C API)rN  platform_versionrS  s    r3   using_pjrt_c_apir|  v  s    	W->>	>>r2   c                    t                t        |       }t        5  |t        v rt        |   |fi |cd d d        S 	 d d d        t	        d| z        # 1 sw Y   xY w)Nztopology not implemented for %s)r  r  r   ru   NotImplementedError)r  topology_namekwargsactual_platforms       r3   make_pjrt_topologyr  y  sk    %')(3/ K-- 1-J6JK K-K 	=HIIK Ks   AAc                ^   t        j                  d      sBt               }|t        d      t        j                  d|      }t        j                  |       t        j                  d      sJ t        j                  d      st        j                  d       t        j                  | fi |S )NrI   zkJAX TPU support not installed; cannot generate TPU topology. See https://github.com/jax-ml/jax#installation)
r   rJ   r   r   rK   r   rL   rM   rN   #make_tfrt_tpu_c_api_device_topology)r  r  rP   rR   s       r3   make_pjrt_tpu_topologyr    s    		&	&u	-')L89 9 33E<HE&&u-		&	&u	--	-		+	+E	2%%e,		7	7

 r2   c                p    t               r,t        t        j                  |       |k(  ry t        |  d      y )Nz config should be updated before backends are initialized i.e. before any JAX operation is executed. You should initialize this config immediately after `import jax`.)r  rb  r
   r   )r#   new_vals     r3   !_validate_backend_not_initializedr    sC    v}}d#w.
& B 	BC C  r2   jax_num_cpu_devicesr   zNumber of CPU devices to use. If not provided, the value of the XLA flag --xla_force_host_platform_device_count is used. Must be set before JAX is initialized.)r#   r$   r   	validator*jax_cpu_get_local_topology_timeout_minutesr,   zgTimeout in minutes for getting the local topology of each CPU device when building the global topology.+jax_cpu_get_global_topology_timeout_minutes   zTimeout in minutes for getting the global topology of CPU devices; should be strictly greater than `--jax_cpu_get_local_topology_timeout_minutes`.)returnz5xla_client._xla.TransferServerInterfaceFactory | None)NN)rP   
str | NonerQ   z_NameValueMapping | None)rX   floatr  rT   )r#   r   rd   rc   rf   re   rh   rg   ri   rg   r}   TopologyFactory | NonerR   r   r  Noner  )r   z%xla_client._xla.CpuCollectives | Noner  xla_client.Client)r   r   r  re   )r   r   r  rr   )r   r   r  zEtuple[str, Mapping[str, str | int | list[int] | float | bool] | None])r  r  )r   r   rQ   .OptionsDict | Callable[[], OptionsDict] | Noner  r  )r   r   rf   re   rP   r  rQ   r  rR   r   rd   zBackendFactory | Noner}   r  r  r   )r  r   )r  r   r  rg   )r  r   r  r   )r  r   r  z	list[str])r  rg   )r  rp   )r  r   r  r  )r  zNone | str | xla_client.Clientr  r  )rP  zxla_client.Device | Noner  r  )r1  str | xla_client.Client | Noner  re   )r1  r  r  list[xla_client.Device])r  r   )r  ztuple[int, int] | None)r  
int | None)r  zSequence[int] | None)NNN)rA  r  r1  r  ri  r  r  r  )r1  r  r  z	list[int])r   )r  r   )__doc__
__future__r   r   collections.abcr   r   dataclasses	functoolsr   r   r   loggingr   r   r  r7  rZ   typingr   r   r	   r.   jax._srcr
   r   r   r   r   jax._src.cloud_tpu_initr   jax._src.libr   r   r   	getLoggerrj   r   rm   r   r   r   er   register_exclusion__file__r   r   MIN_COMPUTE_CAPABILITYstring_flagrG  r   lowerBACKEND_TARGETrH  r   r   int_flagr   r   	bool_flagr   r=   r@   rD   rE   r4   r!  r   re   r%  r  rg   _NameValueMappingrG   rS   r`   Clientrc   DeviceTopologyTopologyFactory	dataclassrb   rn   ro   rq   rs   Lockr   rt   r   ru   rv   r   ry   r{   r   r   r   r   r   r   r]   OptionsDictr   r   r   r  r  r  r   	_platform_alias
setdefaultr  r	  r  r  r  r  r  r  r  r+  r=  r(  rJ  cacherN  rQ  rB  rU  rW  rY  r^  rc  rf  rC  rA  ri  rh  ru  rw  ry  r|  r  r  r  	int_stater   r   r   r1   r2   r3   <module>r     sA   #  -      	     $     # #  8 #  "			8	$  " ! !( + 58E ' 9  "v!!r	:< $##BII"B'--/	QS
 $##BII!2&,,.	:< *v))35 
 +**35  )	!
  'F&&	 
J  .V--	(
%  &8V%7%7	1
O& " "4!3!3	-	M	"  '6foo-	' # %4FOO+	4% !" #  CsCcE4'G!HHI O:O0 JN.F,8 "eJ$5$5t$;<<=3j&?&?&E FFG  * 68 2 7-1 * 1+-	( -#%. %	 ! T !y~~24 / 4! 9 !&	(  '-f%5 ( 5 $+) x + ./2627EI15.'*.+/. ,0. -C	.
 %/.
 ;?.  :>.6..b 	?QU9 *t	<s
:@@@*AHH"H c39tCy0584??@
 ?C"";" "P #>B%),0AA A 	A
 <A A #A *A 	AHM:!. 
 
 -/ ) .*002 ?Iv  ,33I>?'E*7&)*=J4@	: 04,6 T6/3),)) 7) (,$ /32+22. /38+88 /3(+((8$

	/	= T6.2<@(,K9K%K1HK 7K> /3.+..(  T6.2!+!! 7!  /3-+--$ /3"+""?J C #&""		2 79NO *:)9)9	5	. 7BD	* & +;&*:*:	6	; 7CE
+ 'y#  + ,,115+s   T U
'U
+UU
