
    Vpf                       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	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Zddl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#  ej$        e%          Z&de'd<   	 ddl(Z(n2# e)$ r dZ(Y n)e*$ r"Z+e&,                    de+           dZ(Y dZ+[+ndZ+[+ww xY w ej-        e.           e"j/        Z0dZ1 ej2        ddd          Z3 ej2        d ej4        dd          5                                d          Z6 ej2        d ej4        dd          5                                d          Z7 ej2        ddd          Z8 ej2        ddd           Z9 ej:        d!dd"#          Z; ej<        d$d%d&#          Z=g d'Z> ej?        d(d)e>d*e> +          Z@ ej<        d,d%d-#          ZAd. ZBd%aCdd3ZDeg ee"j/        df         f         ZEed4ee"jF        df         f         ZGejH         G d5 d6                      ZIi ZJd7e'd8<   daKd2e'd9<   i aLd:e'd;<   i aMd<e'd=<    ejN                    ZOd%aPd>e'd?<    ejN                    ZQi ZRd@e'dA<   g ZSdBe'dC<    ejN                    ZTdDdEhZUdFe'dG<   ddHd%dddIddVZV	 dddZZW eVd[eWdd%\           d] ZX	 	 ddd`ZYdddZZ e[e"de          r6 eVdD e
eZdDe8f          dgdH\            eVdE e
eZdEe9f          dgdH\            e[e"dh          r eVdi e
eDdjk          dldH\           ddnZ\ddqZ]ddrZ^ds Z_dtddddudd|Z`dd}Zad~ ZbdddZci Zdde'd<   ece                                D ].\  ZfZgedh                    egg           i                    ef           /ddZjddZkddZld ZmddZnd ZoddZpd ZqddZrddZs	 dddZt e	d          	 ddd            Zu	 dddZv	 dddZw	 dddZx	 dddZyddZzdddZ{dddZ|e		 	 	 ddd            Z}	 dddZ~dddZe		 ddd            ZdddZ	 dddZddZdddZddZdS )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)	lru_cachepartial)AnyUnion)config)distributed)hardware_utils)traceback_util)util)get_tpu_library_path)cuda_versions)
xla_client)xla_extension
Any | Nonejax_pluginsz Failed to import jax_plugins: %s4   jax_xla_backend z/Deprecated, please use --jax_platforms instead.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_processeszIMock number of JAX processes in GPU client. Value zero turns off mocking.)namedefaulthelpjax_cpu_enable_gloo_collectivesFzBDeprecated, please use jax_cpu_collectives_implementation instead.)nonegloompi"jax_cpu_collectives_implementationr$   zDCross-process collective implementation used on CPU. Must be one of )r    r!   enum_valuesr"   jax_cpu_enable_async_dispatchzcOnly applies to non-parallel computations. If False, run computationsinline without async dispatch.c                 >    t          j        dt          d           d S )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     S/var/www/html/nettyfy-visnx/env/lib/python3.11/site-packages/jax/_src/xla_bridge.py_at_forkr3   z   s0    
-Hq" " " " " "r1   
timer_secsfloatreturnxla_client.Client | Nonec                     fd}t          j         |          }|                                 	 t          j        t                      t          d                    }|                                 n# |                                 w xY w|S )Nc                 8    t          j        d  d           d S )Nz/TPU backend initialization is taking more than z seconds. Did you run your code on all TPU hosts? See https://jax.readthedocs.io/en/latest/multi_process.html for more information.)r-   r.   r4   s   r2   _log_warningz/tpu_client_timer_callback.<locals>._log_warning   s7    M
       r1   tpu)	threadingTimerstartr   make_tpu_clientr   _options_from_jax_configscancel)r4   r;   tclients   `   r2   tpu_client_timer_callbackrE      s         oj,//!'')))'!%((* *F HHJJJJAHHJJJJ	-s   .A4 4B
.c                  N    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<   d	S )BackendRegistrationBackendFactoryfactoryintpriorityFboolfail_quietlyexperimentalNr   c_api)__name__
__module____qualname____annotations__rM   rN   rO   r0   r1   r2   rG   rG      sb          ---
 , , %r1   rG   zdict[str, BackendRegistration]_backend_factories_default_backenddict[str, xla_client.Client]	_backendsdict[str, str]_backend_errorsrL   _plugins_registeredzdict[str, TopologyFactory]_topology_factoriesz	list[Any]_plugin_callbackscudarocmzset[str]_nonexperimental_pluginsTrK   rM   rN   make_topologyrO   r    strrI   rH   rK   rJ   rM   rN   ra   TopologyFactory | NonerO   Nonec                   t           5  | t          v rt          d|  d          	 d d d            n# 1 swxY w Y   t          |||||          t          | <   ||t
          | <   d S d S )NzBackend z already initialized)_backend_lockrW   RuntimeErrorrG   rT   r[   )r    rI   rK   rM   rN   ra   rO   s          r2   register_backend_factoryrh      s      @ @y>D>>>??? @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ 1X|\5: :T - s   266collectives%xla_client._xla.CpuCollectives | Nonexla_client.Clientc                `   | t           j        }t          j        rd}t          j        dt
                     |dk    r0t          j                            t          j
        j                  } ns|dk    rLt          j                                        } |                                  t          j        | j                   n!|dk    rt#          d| dt$           d	          t          j        t(          j        t          j
        j        t          j
        j        t          j
        j        | 
          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.
  Nr%   zSetting `jax_cpu_enable_gloo_collectives` is deprecated. Please use `jax.config.update("jax_cpu_collectives_implementation", "gloo")` instead.)distributed_clientr&   r$   z#Unknown collectives implementation z . Available implementations are .)asynchronousrm   node_id	num_nodesri   )CPU_COLLECTIVES_IMPLEMENTATIONvalue_CPU_ENABLE_GLOO_COLLECTIVESr-   r.   DeprecationWarningr   _xlamake_gloo_tcp_collectivesr   global_staterD   make_mpi_collectivesInitatexitregisterFinalizerg   CPU_COLLECTIVES_IMPLEMENTATIONSmake_cpu_client_CPU_ENABLE_ASYNC_DISPATCH
process_idnum_processes)ri   collectives_impls     r2   r   r      s@   & 5;#) ! P )	 	 	
 6!!O==&3: >  kk 
U	"	"O88::kok*++++	V	#	# >+> >:> > > ? ? ? 
	#+1"/6$/&4
 
 
 r1   cpurK   rM   c           
         | D ]P}t          j        |          }|t          k     r/t          j        d| d|dz   dt          dz   dt
                     Qd S )NzDevice z has CUDA compute capability 
   z> which is lower than the minimum supported compute capability zX. See https://jax.readthedocs.io/en/latest/installation.html#nvidia-gpu for more details)r   cuda_compute_capabilityMIN_COMPUTE_CAPABILITYr-   r.   r/   )devices_to_checkidxcompute_caps      r2   _check_cuda_compute_capabilityr     s     
 
c7<<K+++m	# 	 	KN 	 	!"$	 	 	
 	  
 
r1   raise_on_first_errordebugc                |   	 t           J g 		 d)d*d
	 	 d+d, 	fd} |dt           j        t           j        dd            |dt           j        t           j        dd            |dt           j        t           j        d            |dt           j        t           j        dd            |dt           j	        t           j
        d            |dt           j        t           j        dd            |d t           j        t           j        dd!           g }g }	D ]E}|d"         }|d#         r|d$         s|                    |           0|                    |           Fd%d& d%}|r%t!          d'|                    |                      |r%t%          d(|                    |                     d S )-NFr    rb   runtime_versionrJ   build_versionmin_supported	debug_msgrL   c           
     ^    |rd|  d| d| d| S |rd| d}nd}d|  d	| d| d| d
| 
}|S )Nz	Package: z 
Version JAX was built against: z
Minimum supported: z
Installed version: z5The local installation version must be no lower than rn   z[The local installation must be the same version as the version against which JAX was built.z	Outdated z4 installation found.
Version JAX was built against: 
r0   )r    r   r   r   r   req_strmsgs          r2   	_make_msgz'_check_cuda_versions.<locals>._make_msg(  s    
  76$ 6 60=6 6$16 6 %46 6 7  =%!% % %gg<gt  -: !.  "1  	 C
 Jr1      r   scale_for_comparisonmin_supported_versionc                    |            }	  |            }nb# t           $ rU}d|  d}rt          |          ||dt          j                     z  }                    | d|d           Y d}~dS d}~ww xY w|s||z  }||k    }	|	rrD | ||||	          }
|	srt          |
          | d|
|	|||d	}                    |           dS dS )
al  Checks the runtime CUDA component version against the JAX one.

    Args:
      name: Of the CUDA component.
      get_version: A function to get the local runtime version of the component.
      get_build_version: A function to get the build version of the component.
      scale_for_comparison: For rounding down a version to ignore patch/minor.
      min_supported_version: An absolute minimum version required. Must be
        passed without rounding down.

    Raises:
      RuntimeError: If the component is not found, or is of unsupported version,
        and if raising the error is not deferred till later.
    zUnable to load z. Is it installed?r   F)r    	installedr   N)r    r   r   r   r   T)r    r   r   passedr   versionminimum_supported)	Exceptionrg   	traceback
format_excappend)r    get_versionget_build_versionr   r   r   r   eerr_msgr   r   recordr   r   r   resultss               r2   _version_checkz,_check_cuda_versions.<locals>._version_check?  sj   ( &%''Mgg   :$:::g	 +7##*.i*,,...gnndwGGHHHfffff ! D+/CC"g-F U I4&-$1$9 &	( ( (c
  
, 
3#"#0$'<> > 	v! s   
 
A7A
A22A7CUDAr   i.  )r   r   cuDNNd   i#  cuFFT)r   cuSOLVERi,  cuPTI   )r   cuBLASi$ cuSPARSEiD/  r   r   r   r   z2--------------------------------------------------z CUDA components status (debug):
zIUnable to use CUDA because of the following issues with CUDA components:
)F)
r    rb   r   rJ   r   rJ   r   rJ   r   rL   )r   r   )r    rb   r   rJ   r   rJ   )r   cuda_runtime_get_versioncuda_runtime_build_versioncudnn_get_versioncudnn_build_versioncufft_get_versioncufft_build_versioncusolver_get_versioncusolver_build_versioncupti_get_versioncupti_build_versioncublas_get_versioncublas_build_versioncusparse_get_versioncusparse_build_versionr   printjoinrg   )
r   r   r   errorsdebug_resultsresultmessagejoin_strr   r   s
   ``      @@r2   _check_cuda_versionsr   #  s   		"	"	""$' #(	    4 2323	3 3 3 3 3 3 3 3 3 3j .?9&(',. . . . .%'  	 	 	 	 .-92&)+ + + + .]?5&)',	. . . .
 .-92')+ + + + .=;3&)'-	/ / / /
 .]?5&)',	. . . . &- $ $f%=G+ $fX&6 $mmG7####(( -	 ,]]=)), , - - - 3
 2"--//2 2 3 3 33 3r1   platform_namevisible_devices_flagconfig.Flag[str]c                   |j         }d }|dk    rd |                    d          D             }t          j         dk    }|rt          j         nt          j        j        }| dk    ret          j        d          st                       nt          d           |r|nt          t          j                              }t          |           t          j        t          j        j        t          j        j        || ||          S )	Nr   c                ,    h | ]}t          |          S r0   rJ   .0xs     r2   	<setcomp>z"make_gpu_client.<locals>.<setcomp>  s    BBB!s1vvBBBr1   ,r   r]   JAX_SKIP_CUDA_CONSTRAINTS_CHECKzeSkipped CUDA versions constraints check due to the JAX_SKIP_CUDA_CONSTRAINTS_CHECK env var being set.)rm   rp   rq   r   allowed_devicesmock)rs   split_MOCK_NUM_PROCESSESr   rx   r   osgetenvr   r   ranger   cuda_device_countr   r   make_gpu_clientrD   r   )r   r   visible_devicesr   use_mock_gpu_clientrq   r   s          r2   r   r     s'    ).//BB'<'<S'A'ABBBO+1A5 
2#1 
 f9677 B A B B B
 	6=24455 
 ##3444		#$18&1!%
 
 
 r1   r   )r   r      r@   r<   g      N@r:   i,  plugins_from_envc                    | si S i }|                      d          D ][}	 |                     t          j        j                  \  }}|||<   0# t          $ r t
                              d||            Y Xw xY w|S )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.
  r   z;invalid value %s in env var PJRT_NAMES_AND_LIBRARY_PATHS %s)r   r   pathpathsep
ValueErrorloggerwarning)r   pjrt_pluginspluginr    library_paths        r2   (_get_pjrt_plugin_names_and_library_pathsr     s     
 I, &&s++ 	 	f!<<88dL'l4   nn
G

     
s   ,A&A54A5	json_pathEtuple[str, Mapping[str, str | int | list[int] | float | bool] | None]c                    t          |           5 }t          j        |          }ddd           n# 1 swxY w Y   d |j                    vrt	          d          |d          |j        d          fS )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.
  Nr   z<PJRT plugin config file should contain "library_path" field.create_options)openjsonloadkeysr   get)r   fr
   s      r2   _get_pjrt_plugin_configr     s     I !Yq\\F              ;6;==((
F   
 *&*-=">">	??s   155c                 N   t                      } t          rdt          j        t          j        t          j        dz             D ]6\  }}}t                              d|           |                     |           7nt                              d           ddl	m
}  |d          D ]<}t                              d|j                   |                     |j                   =| D ]}t                              d	|           d
}	 t          j        |          }nP# t          $ r t                              d|           Y n)t           $ r t                              d           Y nw xY w|r8	 |                                 #  t                              d|           Y xY wd
S )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 implementors 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.
  rn   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__rP   r   r   addimportlib.metadatar   rs   	importlibimport_moduleModuleNotFoundErrorr   ImportError	exception
initialize)plugin_modules_r    r   entry_pointplugin_module_nameplugin_modules          r2   discover_pjrt_pluginsr  #  s/   4 55.  @*k2S8   
4 ll94@@@	 LL>??? .-----!\666 * *k
LL>"$ $ ${()))) + H H
LL+-?@@@M.-.@AAmm ; ; ;nn &'9; ; ; ; ; . . . - . . . . ..  HH  """"H 34F	H 	H 	H 	H 	H	HH Hs$   D%E'#E'&E'-FF!c                   i }t           j        j        }g }|r|                    d          }|D ]N}|                    d          }t	          |          dk    rt          d| d          |d         ||d         <   O| dk    rVt          j        }|d	k    r"d
 |                    d          D             |d<   t          j        }|dk    |d<   |d         r||d<   |S )N;:r+   zGMultiple ':' separators for option in jax_pjrt_client_create_options: 'z"'. Should be in format 'key:value'r   r   r]   r   c                ,    g | ]}t          |          S r0   r   r   s     r2   
<listcomp>z-_options_from_jax_configs.<locals>.<listcomp>{  s    #O#O#OqCFF#O#O#Or1   r   r   enable_mock_ncclrq   )r
   jax_pjrt_client_create_optionsrs   r   lenrg   CUDA_VISIBLE_DEVICESr   )plugin_nameoptionspjrt_client_optionspjrt_client_option_listoptionoption_listr   mock_processess           r2   rA   rA   g  s"   '=C =177<<' - -f,,s##KKA,.4, , ,- - - *!nGKNF*0O%#O#OO4I4I#4N4N#O#O#Og (.N"01"4G!" ,+gk	.r1   i  )rK   r   r  rO   r  r   
str | Noner  9Mapping[str, str | int | list[int] | float | bool] | Noner   c          	          fd}|r|rt                               d            dS |s|st                               d            dS t                               d |           |5t          j         |          }t          j                            |           n|J t          j         |           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.
    c_api: Optional. The plugin can provide a PJRT C API to be registered.
  c                    t          j                  st          j                   i } |                                |                     t	                               t
          j        j        t          j        | d           S t
          j        j	        t
          j        j
        d}|                    |            t          j        |t
          j        j                  S )N)rp   rq   )r   pjrt_plugin_initializedinitialize_pjrt_pluginupdaterA   r   rx   rD   make_c_api_clientr   r   )updated_optionsdistribute_optionsr  r  s     r2   rI   z register_plugin.<locals>.factory  s    -k:: 5'444OW%%%4[AABBB&.)+MMM +6 -;  000'')A)H  r1   zHBoth library_path and c_api are provided when registering PJRT plugin %sNzGNeither library_path nor c_api provided when registering PJRT plugin %s"registering PJRT plugin %s from %sFr`   )r   errorr   r   load_pjrt_plugin_dynamicallyprofilerregister_plugin_profilerload_pjrt_plugin_with_c_apir   make_c_api_device_topologyr_   rh   )r  rK   r   r  rO   rI   ra   rN   s   `  `    r2   register_pluginr0    sK   &     (  e 
LL	  
 F	 e 
LL	  
 F,,*K   3KNNE007777*;>>>*?GG-$<<,;((-L)6eE E E E 
,r1   c                 2   t          t          j        dd                    } |                                 D ]_\  }}|                    d          rt          |          \  }}n|}d}t                              d||           t          |||           `dS )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)  )r   r  )	r   r   r   itemsendswithr   r   r   r0  )r   r  r   r   r  s        r2   'register_pjrt_plugin_factories_from_envr5    s     :i.33 , (--// 	M 	Mk4}}W 5d;;lGGlg
LL,k<   KlGLLLLL	M 	Mr1   c                 L   t           5  t          s|t                       t                       t          5  t
                                          D ]$} | j        t          D ]} || j                   %	 d d d            n# 1 swxY w Y   dad d d            d S # 1 swxY w Y   d S )NrO   T)	_plugin_lockrZ   r  r5  _plugin_callback_lockrT   valuesrO   r\   )rI   callbacks     r2   #_discover_and_register_pjrt_pluginsr<    sE   
  ! ! !  .///  , ,)0022 	, 	,G]&- , ,hW]+++++	,, , , , , , , , , , , , , , ,
 !! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !s4   +B?A?3B?B	BB	BB Bgpur]   r^   zdict[str, list[str]]_alias_to_platformsplatformc                n    | t                                           v p| t                                          v S N)rT   r   _platform_aliasesr@  s    r2   is_known_platformrE    s8     (--//
/ /
',,..
.0r1   c                   t                               | d          }|| S t                      }|D ]}||                                v r|c S t	          d|  d|  dd                    |                                          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: r   )r?  r   backendsr   rg   r   )r@  	platformsbps       r2   canonicalize_platformrK    s     "%%h55)Ojj!  aAFFHH}}hhh  /( / /8@/ / /14!&&((1C1CD 	E 	E Er1   	list[str]c                :    t                               | | 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   rD  s    r2   expand_platform_aliasrN  (  s     
	 	 H:	6	66r1   c                
    | dv S )Nr>  r0   rD  s    r2   is_gpurP  0  s    	%	%%r1   c                 t    t           5  t          t                    dk    cddd           S # 1 swxY w Y   dS )z7Returns true if backends have already been initialized.r   N)rf   r  rW   r0   r1   r2   backends_are_initializedrR  4  sz      y>>Q                 s   -11c                    t           5  t          r5t                                          D ]}|j         | |j                   nt
                              |            ddd           dS # 1 swxY w Y   dS )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.
  Nr7  )r9  rZ   rT   r:  rO   r\   r   )r;  rI   s     r2   register_plugin_callbacksrT  :  s      ) ) )'..00 ( ('=$
(
'
'
'
'( x((() ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )s   AA,,A03A0c                 t   t                       t          5  t          rt          cd d d            S t          s1t	          t
          d          rt          j        t                     dat          j	        j
        x} rg }|                     d          D ]$}|                    t          |                     %t          t          |          dd          }dgt          |          z  }t!          t#          |||                    }n#d t$                                          D             }d	}|D ]\  }}}	 |d
k    rt)          j                    s!t-          |          }	|	t          |<   ||k    r|	a|}E# t0          $ rq}
d| d|
 }|r2t3          |
          t4          |<   t6                              |           n+t          j	        j
        r|dz  }n|dz  }t;          |          Y d }
~
d }
~
ww xY wt.          J t          j	        j
        st=                       t          cd d d            S # 1 swxY w Y   d S )Nregister_at_fork)beforeTr   r   Fc                2    g | ]\  }}||j         |j        fS r0   r   )r   r@  registrations      r2   r  zbackends.<locals>.<listcomp>l  s9          $h \*L,E
F     r1   ir]   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<  rf   rW   _at_fork_handler_installedhasattrr   rV  r3   r
   jax_platformsrs   r   extendrN  r   r  listziprT   r3  r   has_visible_nvidia_gpu_init_backendrU   r   rb   rY   r   inforg   _suggest_missing_backends)r]  rH  r@  
prioritiesfail_quietly_listplatform_registrationsdefault_priorityrK   rM   backenderrr   s               r2   rG  rG  O  s    &''' 5 5 5 5 5 5 5 5 5 5
 & ('"6H*I*I (****#' ,22} i#))#.. : :(.x889999YB//j !'C	NN2#Iz#455 7  7     %%''     
 ,B & &((L&vn&K&M&M
))%	(&&&$
%
 
& 
& 
&E8EEEE 	&&)#hh/(
#
++g



!' A]]GG  A  AGW%%
% 



	
& '''% "!!!k5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5sN   H-DH-6E4H-#E43H-4
G/>A'G*%H-*G//1H--H14H1c                     t          j                    dk    rd S t          J t          j        } dt          vrt          j                    r{t          t          d          rFdt          v r=t          d         }d| d}d|v r|dz  }|dz  }t                              |           d S t                              d	|  d           d S d
t          vr=t          j                    d         dk    r"t                              d|  d           d S d S d S )NLinuxr]   GpuAllocatorConfigz#CUDA backend failed to initialize: rn   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://jax.readthedocs.io/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 r<   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systemrU   r@  rW   r   ra  r\  r   rY   r   r   %num_available_tpu_chips_and_device_id)default_platformrj  warning_msgs      r2   rd  rd    sd   W$$ F		%	%	%%.9!F!H!H}233 -/8Q8QF#c@#@@@k	8C	?	?8	
 LLknn[!!!!!nn ,(, , , - - - - - I."V"X"XYZ"[^_"_"_
NN 3/3 3 3 4 4 4 4 4 "_"_r1   c                     t                               d           t          5  i ai ad ad d d            n# 1 swxY w Y   t                                           d S )NzClearing JAX backend caches.)r   rc  rf   rW   rY   rU   get_backendcache_clearr0   r1   r2   _clear_backendsrv    s    
 	++,---  IO              
 s   599c           	        t                               | d           }|:t          d|  dt          t                                                      d          |j        rt                              d|  d           t                              d|            |	                                }|t          d|  d          |
                                d	k    rt          d|  d
          t          j        d|j        fd|                                fd|
                                fd|                                f           t                              d|            |S )N	Backend 'z(' is not in the list of known backends: rn   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)rT   r   rg   r_  r   rN   r   r   r   rI   r{  r   distributed_debug_logr@  rz  r|  )r@  rZ  ri  s      r2   rb  rb    s   #''$77,
	.H 	. 	."''))**	. 	. 	./ / /  @
NN ? ? ? ? @ @ @,,*H555  ""' _
CCCC
D
DDq  
C8CCC
D
DD3W5EF-w/D/D/F/FG,g.B.B.D.DE-w/D/D/F/FGI I I 	,,)8444	.r1   None | str | xla_client.Clientc           
        | t          | t                    s| S | pt          j        pt          j        pd } t                      }| t          |           } |                    | d           }|[| t          v r0t          d|  dt          |           dt          |                     t          d|  dt          |                     |S t          J t          S )Nrx  z' failed to initialize: z. Available backends are zUnknown backend )
isinstancerb   _XLA_BACKENDrs   _PLATFORM_NAMErG  rK  r   rY   rg   r_  rU   )r@  bsri  s      r2   _get_backend_uncachedr    s   
 *Xs";";OL,,L0DL(zz"$X..HffXt$$G	_	$	$ @x @ @-h7@ @59"XX@ @ A A 	A 
JX
J
JR
J
JL L LN'''r1   )maxsizec                     t          |           S rB  )r  rD  s    r2   rt  rt    s     
x	(	((r1   devicexla_client.Device | Nonec                0    | | j         S t                      S )zEReturns the Backend associated with `device`, or the default Backend.)rD   rt  )r  s    r2   get_device_backendr    s     =	r1   ri  str | xla_client.Client | Nonec                ^    t          t          |                                                     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.

  )rJ   rt  r{  ri  s    r2   r{  r{    s&    & 
[!!..00	1	11r1   c                ^    t          t          |                                                     S )z:Returns the number of devices addressable by this process.)rJ   rt  local_device_countr  s    r2   r  r    s&     
[!!4466	7	77r1   list[xla_client.Device]c                D    t          |                                           S )a1  Returns a list of all devices for a given backend.

  .. currentmodule:: jaxlib.xla_extension

  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.
  )rt  devicesr  s    r2   r  r  $  s    2 
W			%	%	'	''r1   c                 *    t          d          j        S )z5Returns the platform name of the default XLA backend.N)rt  r@  r0   r1   r2   default_backendr  @  s    	T			##r1   tuple[int, int] | Nonec                    t          |           }t          |d          rt          |d          r|j        |j        fS dS )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)rt  r\  r  r  r@  ri  s     r2   backend_pjrt_c_api_versionr  E  sU    
 !!'W011 Pg)7 7 P ,g.NOO	r1   
int | Nonec                B    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 methon 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)rt  getattrr  s     r2   backend_xla_versionr  R  s#     !!'	-	.	..r1   rz  host_idc                    |t          j        d           |  !t          |                                           d cxk    rt	          |          k     sn t          d             fdt          |          D             S )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.
  NzThe 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 c                *    g | ]}|j         k    |S r0   rz  )r   drz  s     r2   r  z!local_devices.<locals>.<listcomp>z  s%    	J	J	JM)I)I!)I)I)Ir1   )r-   r.   rt  rz  process_countr   r  )rz  ri  r  s   `  r2   r|  r|  ^  s    $ M	   M((6688M
}
5
5
5
5}W55
5
5
5
5
=m==
>
>>	J	J	J	JWW%%	J	J	JJr1   c                D    t          |                                           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.
  )rt  rz  r  s    r2   rz  rz  }  s      
W			+	+	-	--r1   c                H    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.   rz  r  s    r2   r  r    +    
-=> > > 
w		r1   c                T    t          d t          |           D                       dz   S )z@Returns the number of JAX processes associated with the backend.c              3  $   K   | ]}|j         V  d S rB  r  )r   r  s     r2   	<genexpr>z process_count.<locals>.<genexpr>  s$      77Q_777777r1   r   )maxr  r  s    r2   r  r    s.    
 
77gg&6&6777	7	7!	;;r1   c                H    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.   r  r  s    r2   
host_countr    r  r1   	list[int]c                |    t          j        d           t          t          t	          |                               S )Nzjax.host_ids has been deprecated; please use range(jax.process_count()) instead. jax.host_ids will eventually be removed; please update your code.)r-   r.   r_  r   r  r  s    r2   host_idsr    s=     -   
eM'**++	,	,,r1   c                .    dt          |           j        v S )Nz
PJRT C API)rt  platform_versionr  s    r2   using_pjrt_c_apir    s    	W-->	>>r1   c                    t                       t          |           }t          5  |t          v rt          |         |fi |cd d d            S 	 d d d            n# 1 swxY w Y   t	          d| z            )Nztopology not implemented for %s)r<  rK  rf   r[   NotImplementedError)r@  topology_namekwargsactual_platforms       r2   make_pjrt_topologyr    s    %''')(33/ K K--- 1-JJ6JJK K K K K K K K-K K K K K K K K K K K K K K K 	=HIIIs   AA"Ac                p   t          j        d          sSt                      }|t          d          t          j        d|          }t           j                            |           t          j        d          sJ t          j        d          st          j        d           t          j	        | fi |S )Nr<   zkJAX TPU support not installed; cannot generate TPU topology. See https://github.com/google/jax#installation)
r   pjrt_plugin_loadedr   rg   r+  r,  r-  r#  r$  #make_tfrt_tpu_c_api_device_topology)r  r  r   rO   s       r2   make_pjrt_tpu_topologyr    s    		&u	-	- 8'))L89 9 9 3E<HHE00777		&u	-	----		+E	2	2 -%e,,,		7
 

 
 r1   )r4   r5   r6   r7   )r    rb   rI   rH   rK   rJ   rM   rL   rN   rL   ra   rc   rO   r   r6   rd   rB  )ri   rj   r6   rk   )FF)r   rL   r   rL   )r   rb   r   r   r6   rk   )r   rb   r6   rX   )r   rb   r6   r   )r6   rd   )r  rb   rK   rJ   r   r  r  r   rO   r   r6   r   )r@  rb   r6   rL   )r@  rb   r6   rb   )r@  rb   r6   rL  )r6   rL   )r6   rV   )r@  rb   r6   rk   )r@  r~  r6   rk   )r  r  r6   rk   )ri  r  r6   rJ   )ri  r  r6   r  )r6   rb   )r6   r  )r6   r  )NNN)rz  r  ri  r  r  r  r6   r  )ri  r  r6   r  )r   )r@  rb   )__doc__
__future__r   r{   collections.abcr   r   dataclasses	functoolsr   r   r  r   loggingr   r   r@  rn  r=   r   typingr   r	   r-   jax._srcr
   r   r   r   r   jax._src.cloud_tpu_initr   jax._src.libr   r   r   	getLoggerrP   r   rS   r   r  r  r   r*  register_exclusion__file__Client
XlaBackendr   string_flagr  r   lowerBACKEND_TARGETr  r  _ROCM_VISIBLE_DEVICESint_flagr   	bool_flagrt   r~   	enum_flagrr   r   r3   r[  rE   rH   DeviceTopologyTopologyFactory	dataclassrG   rT   rU   rW   rY   Lockrf   rZ   r8  r[   r\   r9  r_   rh   r   r   r   r   r\  r   r   r  rA   r0  r5  r<  rC  r?  r3  	_platform_alias
setdefaultr   rE  rK  rN  rP  rR  rT  rG  rd  rv  rb  r  rt  r  r{  r  r  r  r  r  r|  rz  r  r  r  r  r  r  r  r0   r1   r2   <module>r     s
     # " " " " "  - - - - - - - -     ( ( ( ( ( ( ( (       				                                         # # # # # # # # # # # #       8 8 8 8 8 8 & & & & & & # # # # # # & & & & & &		8	$	$       +++   ,,11555++++++ " !( + + +
  "v!r57 7 $#BI"B''--//LN N
 $#BI!2&&,,..57 7 *v)12 2  +*12 2 
 &fo	
     0v/	*	M       #:"9"9 !1!1	-/	.+	. 	." " "  .V-	(
%   " " " # 
   8 "eJ$5t$;<<=3j&?&E FFG       * 68  7 7 7 7-1  1 1 1 1+-	 - - - -#% % % % %	  !  ! ! ! !y~24  4 4 4 4!  ! ! ! !&	((  '-f%5  5 5 5 5 ./2627EI15. . . . . .  :>/ / / / /d  	?QU   
   7<',F3 F3 F3 F3 F3R# # # #L 7:()) g
3  
 	 	 	 	 g
4  
 	 	 	 	 7:())  	77,>>>   
   :@ @ @ @*AH AH AH AHH  D #IME E E E E EPM M M M:! ! !. 
  
 -/  . . . .*0022 ? ?Iv  ,,33I>>>>0 0 0 0E E E E*7 7 7 7& & &   ) ) )*= = = =J4 4 4@      6 04    6 4/3) ) ) ) ) (,     /32 2 2 2 2. /38 8 8 8 8 /3( ( ( ( (8$ $ $ $

 
 
 
 
	/ 	/ 	/ 	/ 	/ .2<@(,K K K K K> /3. . . . .(          .2< < < < <          /3- - - - -? ? ? ?J J J J J     s   B C(C,C		C