
    Vpf                    *   d dl mZ d dlm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mZmZmZ d dlmZ d dlmZ d dlmZ d d	lmZ d d
lmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dl m!Z!m"Z"m#Z# d dl$m%Z& d dl$m'Z( d dl)m*Z* d dl+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1 d dl2m3Z3m4Z4 d dl5m6Z6m7Z7m8Z8m9Z9m:Z: d dl;Z<e=e>df         Z?e&j@        Z@e=eAdf         ZBeZCdSd ZD G d! d"          ZEd# ZF e:d$d%&          d'             ZG e:d$d%&          d(             ZHdTd1ZI G d2 dejJ                  ZKes  e8e&jK                  eK          ZKdUd6ZL eMeKd7d            eMeKd8d9           dVd=ZN	 dWdXdBZOdYdDZPejQ        ejR        eK<    ejS        d-          ejR        eK<   ejT        ejU        eK<    ejS        d-          ejV        eK<   ejJ        W                    eK           dE ZX ejY        eKeX           dZdJZZdK Z[dL Z\ e:d$d%&          dM             Z]dN Z^e^ej_        eK<   dO Z`e`eja        ejb        <   e`eja        ejc        <   dP Zdedeje        ejb        <   edeje        ejc        <   dQ Zfefej_        ejg        <   dR Zheheja        eji        <   dS )[    )annotations)defaultdict)CallableSequenceN)AnyTYPE_CHECKINGcast)abstract_arrays)api)api_util)	basearray)config)core)dispatch)dtypes)errors)profiler)
xla_bridge)mlir)pxla)xla)
AutoLayoutDeviceLocalLayoutLayout)
xla_client)xla_extension)Sharding)PmapShardingSingleDeviceShardingdevice_replica_id_maphashed_indexnum_addressable_indiceslocal_to_global_shape)	ArrayLikeDLDeviceType)safe_zipunzip3use_cpp_classuse_cpp_methodcache.a	ArrayImplreturnDevicec                T    | j         j        }t          |          dk    sJ |d         S )N   r   )sharding_internal_device_listlen)r+   devicess     N/var/www/html/nettyfy-visnx/env/lib/python3.11/site-packages/jax/_src/array.py_get_devicer6   8   s-    J,'	W					    c                      e Zd ZdZ	 dddZd Zej        dd            Zej        dd            Z	e
d             Ze
d             ZdS )Shardu  A single data shard of an Array.

  Attributes:
    device : Which device this shard resides on.
    index : The index into the global array of this shard.
    replica_id : Integer id indicating which replica of the global array this
      shard is part of. Always 0 for fully sharded data
      (i.e. when there’s only 1 replica).
    data : The data of this shard. None if ``device`` is non-local.
  Ndevicer.   r1   r   global_shapeShapedataNone | ArrayImpl | PRNGKeyArrayc                >    || _         || _        || _        || _        d S N)_device	_sharding_global_shape_data)selfr:   r1   r;   r=   s        r5   __init__zShard.__init__J   s#    DLDN%DDJJJr7   c           	         	 d| j         d| j         d| j         d| j         d	S # t          $ r d| j         d| j         dcY S w xY w)NzShard(device=z, index=z, replica_id=z, data=))r:   index
replica_idr=   
ValueErrorrE   s    r5   __repr__zShard.__repr__Q   s    @Adk A ATZ A A OA A48IA A A B @ @ @?T[??49??????@s   "% AAr-   Indexc                    	 | j         j        }n'# t          $ r t          d| j          d          d w xY w || j                  | j                 }|J |S )Nz(Cannot calculate indices from sharding: z<. Please create a device to index mapping for your sharding.)rB   devices_indices_mapAttributeErrorrK   rC   r:   )rE   device_indices_map_fnrI   s      r5   rI   zShard.indexX   s    ?"n@ ? ? ? 4.4 4 4 5 5:>?? "!$"455dkBELs    $3intc                L    t          | j        | j                  | j                 S r@   )r    rB   rC   r:   rL   s    r5   rJ   zShard.replica_idd   s     1CDDT[QQr7   c                    | j         S r@   )rA   rL   s    r5   r:   zShard.deviceh   s
    <r7   c                    | j         S r@   )rD   rL   s    r5   r=   z
Shard.datal   s
    :r7   r@   )r:   r.   r1   r   r;   r<   r=   r>   )r-   rN   )r-   rS   )__name__
__module____qualname____doc__rF   rM   	functoolscached_propertyrI   rJ   propertyr:   r=    r7   r5   r9   r9   >   s        	 	 8<    @ @ @ 	 	 	 	 R R R R   8   8  r7   r9   c                     | | }|                     |           t          j        |          } |j        j        di ||_        |S )z=Method to reconstruct a device array from a serialized state.r^   )__setstate__r   
device_putavalupdate)funargs	arr_state
aval_statenp_value	jnp_values         r5   _reconstruct_arrayrj   q   sR    S$Z(
	"""nX&&)(9>(66:66).	r7      F)max_sizetrace_context_in_keyc                   |                      |          }t                      }g }t          |                                          D ]D\  }}t	          |          }||vr,|                    |           |                    ||f           E|S r@   )addressable_devices_indices_mapset	enumeratevaluesr!   addappend)sshapemap_seen_h_indiceslarray_indexrI   h_indexs           r5   _cached_index_calcr|   z   s    	
	*	*5	1	1$55.!%dkkmm44 % %k55!!Gn$$!!!hhU#$$$	
(r7   c                8   t          j                    dk    rdS t          d |                     |                                          D                       }t          d |                     |                                          D                       }||k    S )Nr0   Fc                ,    h | ]}t          |          S r^   r!   .0vs     r5   	<setcomp>z3_process_has_full_value_in_mcjax.<locals>.<setcomp>   s    FFF1|AFFFr7   c                ,    h | ]}t          |          S r^   r   r   s     r5   r   z3_process_has_full_value_in_mcjax.<locals>.<setcomp>   s    RRR1|ARRRr7   )r   process_countr3   rP   rr   ro   )ru   rv   num_unique_indicesnum_addressable_unique_indicess       r5    _process_has_full_value_in_mcjaxr      s     1$$5FF 5 5e < < C C E EFFFH H#&RR A A% H H O O Q QRRR$T $T 	=	==r7   arrays Sequence[ArrayImpl | np.ndarray]r1   r   rb   core.ShapedArrayexpected_shaper<   c                    |j         }| D ]g}|j         |k    rt          d|j          d| d|           |j        |k    r2t          d| d|j         d|                                 d|           hdS )	z:Validates that per-device arrays are valid and consistent.z8Input buffers to `Array` must have matching dtypes. Got z, expected z for buffer: zExpected shard shape z- doesn't match the single device array shape z. Shape of Array is z with sharding N)dtyperK   rv   	str_short)r   r1   rb   r   expected_dtypedbs         r5   /_validate_shape_and_dtype_for_per_device_arraysr      s     :.  b	x>!!HH H&4H HCEH H   
x>!!9. 9 9 "9 9^^9 9.69 9   " r7   c                     e Zd ZU ded<   ded<   ded<   ded<   ded	<   d
ed<    e            	 dVdWd            Zd ZedXd            Zed             Z	ed             Z
ed             Zed             Zed             Zed             Zd Zd Zd Zd Zd  Zd! Zd" Zd# Zd$ ZdYd&Zd' Zd( Zd) Zd* ZedZd+            Zd, ZedZd-            Zd[d/Z d.d.d.d.d0d\d9Z!d]d;Z"d< Z# e            d=             Z$e e            d>                         Z% e            d?             Z&d^dAZ'edB             Z(edC             Z)d_dFZ*e+j,        d`dH            Z-edI             Z.ed`dJ            Z/ e            dK             Z0 e            dL             Z1dM Z2 e            dN             Z3 e            dO             Z4 e            dP             Z5e6j7        dQ             Z8e e+j9        e6j7        dRS          dadU                        Z:d.S )br,   r   rb   r   rB   zlist[ArrayImpl]_arraysbool
_committed_skip_checksznp.ndarray | None
_npy_valueFr1   r   Sequence[ArrayImpl]	committedc                    || _         || _        d |D             | _        || _        d | _        |rt
          j        j        r|                                  d S d S )Nc                (    g | ]}|j         d          S )r   )r   r   r+   s     r5   
<listcomp>z&ArrayImpl.__init__.<locals>.<listcomp>   s    111QAIaL111r7   )	rb   rB   r   r   r   r   enable_checksvalue_check_and_rearrange)rE   rb   r1   r   r   r   s         r5   rF   zArrayImpl.__init__   sn     DIDN11&111DLDODO  "6/5 "
!!!!!" "r7   c                z  	 d | j         D             	| j        j        }t          | j                   t          |          k    r4t	          dt          |           dt          | j                              t          	                                          }d |D             }||z  }|r1||z
  }||z
  }d}|r	|d| dz  }|r	|d| d	z  }t	          |          t          | j         | j        | j        | j        	                    | j
                  
           | j        j        }	fd|D             | _         d S )Nc                8    i | ]}t          |          j        |S r^   r6   id)r   r   s     r5   
<dictcomp>z2ArrayImpl._check_and_rearrange.<locals>.<dictcomp>   s#    IIIb;r??-rIIIr7   z	Expected zW per-device arrays (this is how many devices are addressable by the sharding), but got c                    h | ]	}|j         
S r^   r   )r   ds     r5   r   z1ArrayImpl._check_and_rearrange.<locals>.<setcomp>   s    <<<qad<<<r7   z?Addressable devices and per-device arrays devices do not match.z Sharding contains devices z+ that are not present in per-device arrays.z# Per-device arrays contain devices z& that are not present in the sharding.)r1   rb   r   c                *    g | ]}|j                  S r^   r   )r   r:   device_id_to_buffers     r5   r   z2ArrayImpl._check_and_rearrange.<locals>.<listcomp>   s!    PPPv'	2PPPr7   )r   r1   addressable_devicesr3   rK   rp   keysr   rb   shard_shaperv   _addressable_device_assignment)
rE   addressable_devarray_device_idsaddressable_device_idsdiffdev_in_sharding_not_in_arraysdev_in_arrays_not_in_shardingerr_msgaddressable_dar   s
            @r5   r   zArrayImpl._check_and_rearrange   s   IIDLIIIm7O
4<C0000%c/** % %T\""% %& & &
 .335566<<O<<< 44D  &<?O&O#&69O&O#
K 	& B A2O A A A 	B	& = <:W < < < 	=w3Y}00<<	    ]ANPPPPPPPDLLLr7   r-   r<   c                    | j         j        S r@   )rb   rv   rL   s    r5   rv   zArrayImpl.shape       9?r7   c                    | j         j        S r@   )rb   r   rL   s    r5   r   zArrayImpl.dtype   r   r7   c                *    t          | j                  S r@   )r3   rv   rL   s    r5   ndimzArrayImpl.ndim   s    tz??r7   c                4    t          j        | j                  S r@   )mathprodrv   rL   s    r5   sizezArrayImpl.size   s    9TZ   r7   c                    | j         S r@   )rB   rL   s    r5   r1   zArrayImpl.sharding   s
    >r7   c                    |                                   t          | j        t                    rt	          | j        j                  d         S | j        S Nr   )_check_if_deleted
isinstancer1   r   list
device_setrL   s    r5   r:   zArrayImpl.device  sI    $-!566 /$-*++A..=r7   c                    | j         j        S r@   )rb   	weak_typerL   s    r5   r   zArrayImpl.weak_type  s    9r7   c                *    t          | j                  S r@   )str_valuerL   s    r5   __str__zArrayImpl.__str__  s    t{r7   c                b    	 | j         d         S # t          $ r}t          d          |d }~ww xY w)Nr   zlen() of unsized object)rv   
IndexError	TypeError)rE   errs     r5   __len__zArrayImpl.__len__  sC    :Z] : : :/00c9:s    
.).c                R    t          j        |            t          | j                  S r@   )r   check_bool_conversionr   r   rL   s    r5   __bool__zArrayImpl.__bool__  s#    t$$$r7   c                \    t          j        |            | j                                        S r@   )r   check_scalar_conversionr   	__float__rL   s    r5   r   zArrayImpl.__float__  s'     &&&;  """r7   c                \    t          j        |            | j                                        S r@   )r   r   r   __int__rL   s    r5   r   zArrayImpl.__int__  s'     &&&;   r7   c                \    t          j        |            | j                                        S r@   )r   r   r   __complex__rL   s    r5   r   zArrayImpl.__complex__!  s'     &&&;""$$$r7   c                R    t          j        |            t          | j                  S r@   )r   check_integer_conversionhexr   rL   s    r5   __hex__zArrayImpl.__hex__%  #    !$'''t{r7   c                R    t          j        |            t          | j                  S r@   )r   r   octr   rL   s    r5   __oct__zArrayImpl.__oct__)  r   r7   c                \    t          j        |            t          j        | j                  S r@   )r   r   oprI   r   rL   s    r5   	__index__zArrayImpl.__index__-  s%    !$'''8DK   r7   Cc                6    | j                             |          S r@   )r   tobytes)rE   orders     r5   r   zArrayImpl.tobytes1  s    ;u%%%r7   c                4    | j                                         S r@   )r   tolistrL   s    r5   r   zArrayImpl.tolist4  s    ;r7   c                x    | j         dk    rt          | j        d         |          S t          | j        |          S )Nr   r^   )r   formatr   )rE   format_specs     r5   
__format__zArrayImpl.__format__7  s5    yA~~DKO[111DK---r7   c                   ddl m} ddlm} |                                  t          | j        t                    rt          j	        j
        rjt          |t                    r|n|f}t          d |D                       t          d           ft          | j                  t          |          z
  z  z   }nzt          |t                    s-|ft          d           ft          | j                  dz
  z  z   }n8|t          d           ft          | j                  t          |          z
  z  z   }t          | j                            | j                                                            }	 |                    |          }n# t$          $ r d }Y nw xY w|| j        |         }t)          |j        t-          t/          |                    |gdd          }	t          j	        j
        r=t          d	 t1          |          D                       }
|                    |	|

          S |	S |                    | |          S )Nr   )lax)	lax_numpyc              3  l   K   | ]/}t          |t                    rt          ||d z   d          n|V  0dS )r0   N)r   rS   slice)r   is     r5   	<genexpr>z(ArrayImpl.__getitem__.<locals>.<genexpr>G  sW       
 
CDZ3%7%7>E!QUD!!!Q
 
 
 
 
 
r7   r0   FTr   r   c              3  J   K   | ]\  }}t          |t                    |V  d S r@   )r   rS   )r   r   xs      r5   r   z(ArrayImpl.__getitem__.<locals>.<genexpr>^  s5      KKTQ
1c8J8JKqKKKKKKr7   )
dimensions)jax._src.laxr   jax._src.numpyr   r   r   r1   r   r   pmap_no_rank_reductionr   tupler   r3   rv   rP   rr   rI   rK   r   r,   rb   r   r6   rq   squeeze_rewriting_take)rE   idxr   r   cidxpadded_cidxindicesarr_idxr+   outdimss              r5   __getitem__zArrayImpl.__getitem__>  sB         (((((($-.. 		&	, 
L e,,8ss3& 
 
HL
 
 
 
 
4[[Nc$*ooD		9:; #u%% 	L%++3tz??Q3F!GG++uT{{nDJ#c((0JKK+dm77
CCJJLLMMg--,,   		L!F(Q881#   (. 	 KKYt__KKKKK$ST22
2*$$T3///s   0F FFc                     j         dk    rt          d           j        s	 j        sJ t	          j         j                  s j        rd                      d          D             S t           j        t                    r& fdt           j        d                   D             S  fdt           j        d                   D             S )Nr   ziteration over a 0-d arrayc              3  H   K   | ]}|                                 D ]}|V  d S r@   )_unstack)r   chunksls      r5   r   z%ArrayImpl.__iter__.<locals>.<genexpr>k  s9      QQu@P@PQQ"QQQQQQQr7   d   c              3  (   K   | ]}|         V  d S r@   r^   r   r   rE   s     r5   r   z%ArrayImpl.__iter__.<locals>.<genexpr>m  s'      66AQ666666r7   c              3  V   K   | ]#}t          j        j        |                   V  $d S r@   )r   ra   r   r  s     r5   r   z%ArrayImpl.__iter__.<locals>.<genexpr>q  s3      MM1t{1~..MMMMMMr7   )r   r   is_fully_replicatedis_fully_addressabler   is_single_device_shardingr1   _chunk_iterr   r   rangerv   rL   s   `r5   __iter__zArrayImpl.__iter__e  s    yA~~2333%B)BBBB		+DM	:	: Nd>V NQQ 0 0 5 5QQQQdm\22 N6666tz!}!5!56666 NMMMdjm8L8LMMMMr7   c                    | j         j        S r@   )r1   r  rL   s    r5   r  zArrayImpl.is_fully_replicateds  s    =,,r7   c                    d}| j         | j         j        rd| j        j         d}nd| j        j         d}| j        s| j        rt          j                    d         }| j        dk    rd| j	         }nt          j
        | j        |dd	|
          }t          |          |                    d          z
  dz   }d}|t          |          z   dz   |k    rdt          |          z  }| | d| | S | | j	         d	| S )NzArray(zdtype=z, weak_type=True)rH   	linewidthr   z
[], shape=,z, )prefixsuffix	separatormax_line_width
r0    )rb   r   r   namer  r  npget_printoptionsr   rv   array2stringr   r3   rfind)rE   r  	dtype_str
line_widthru   last_line_lenseps          r5   rM   zArrayImpl.__repr__w  s5   Fy!4=4:?===ii-4:?---i  2D$< 2&((5j	a%%%ODKs&*:G G G!ffqwwt}},q0mc	Y	'!	+j	8	8CKK,,,C,,,,1
11i111r7   c                    | j         j        S )a  Is this Array fully addressable?

    A jax.Array is fully addressable if the current process can address all of
    the devices named in the :class:`Sharding`. ``is_fully_addressable`` is
    equivalent to "is_local" in multi-process JAX.

    Note that fully replicated is not equal to fully addressable i.e.
    a jax.Array which is fully replicated can span across multiple hosts and is
    not fully addressable.
    )r1   r  rL   s    r5   r  zArrayImpl.is_fully_addressable  s     =--r7   Nc                D    |i nd|i}t          j        | j        fd|i|S )Ncopyr   )r%  asarrayr   )rE   r   contextr/  kwdss        r5   	__array__zArrayImpl.__array__  s2    22FD>D:dk777$777r7   )streammax_version	dl_devicer/  r4  int | Any | Noner5  tuple[int, int] | Noner6  tuple[DLDeviceType, int] | Noner/  bool | Nonec                   ddl m} | j        j        }t	          |          dk    r t          dt	          |           d          |\  } || |||||          S )Nr   )	to_dlpackr0   znto_dlpack can only pack a dlpack tensor from an array on a singular device, but an array with a Sharding over z devices was provided.)r4  r5  
src_devicer6  r/  )jax._src.dlpackr<  r1   r   r3   BufferError)rE   r4  r5  r6  r/  r<  r   r:   s           r5   
__dlpack__zArrayImpl.__dlpack__  s     *))))))J
:	58__	 	 	  
 GF9T&!, &(	       r7   tuple[enum.Enum, int]c                   t          | j                  dk    rt          d          ddlm} |                                 dk    r	|j        dfS |                                 dk    rlt          |           j        j	        }d|v r|j
        }nd|v r|j        }nt          d	|           t          |           j        }|t          d
          ||fS t          d|                                            )Nr0   z/__dlpack__ only supported for unsharded arrays.r   )r%   cpugpucudarocmz%Unknown GPU platform for __dlpack__: z-Couldn't get local_hardware_id for __dlpack__z@__dlpack__ device only supported for CPU and GPU, got platform: )r3   r   r?  r>  r%   platformkDLCPUr6   clientplatform_versionkDLCUDAkDLROCMlocal_hardware_id)rE   r%   rJ  dl_device_typerM  s        r5   __dlpack_device__zArrayImpl.__dlpack_device__  s2   
4<AIJJJ,,,,,,}}% !##	E	!	!$T**1B	#	#	#%-%%%%- /,/ / 0 0 	0 &d++=		"IJJJ... ]]__   r7   c                r    | j                                         \  }}}d| j        j        i}t          ||||ffS )Nr   )r   
__reduce__rb   r   rj   )rE   rd   re   rf   rg   s        r5   rQ  zArrayImpl.__reduce__  s?    ;1133Cyty23JdIz BCCr7   c                    t          | j                  dk    rt          d          | j        d                                         S )Nr0   z?unsafe_buffer_pointer() is supported only for unsharded arrays.r   )r3   r   rK   unsafe_buffer_pointerrL   s    r5   rS  zArrayImpl.unsafe_buffer_pointer  sF    
4<A " # # #<?00222r7   c                t    t          | j                  dk    rt          d          | j        d         j        S )Nr0   zB__cuda_array_interface__() is supported only for unsharded arrays.r   )r3   r   rK   __cuda_array_interface__rL   s    r5   rU  z"ArrayImpl.__cuda_array_interface__  s?     4<A + , , ,<?33r7   c                |    | j         d         }|                                }|t          | j        j                  z  S )z>Returns the total global on-device size of the array in bytes.r   )r   on_device_size_in_bytesr3   r1   r   )rE   arrper_shard_sizes      r5   rW  z!ArrayImpl.on_device_size_in_bytes  s8     ,q/C0022NC 89999r7   set[Device]c                B    |                                   | j        j        S r@   )r   r1   r   rL   s    r5   r4   zArrayImpl.devices  s    =##r7   c                     t          d          )NzBarr.device_buffer has been deprecated. Use arr.addressable_data(0)rQ   rL   s    r5   device_bufferzArrayImpl.device_buffer  s    
JL L Lr7   c                     t          d          )NzTarr.device_buffers has been deprecated. Use [x.data for x in arr.addressable_shards]r]  rL   s    r5   device_bufferszArrayImpl.device_buffers  s    
\^ ^ ^r7   rI   rS   c                z    |                                   | j        r|                                 S | j        |         S r@   )r   r  _fully_replicated_shardr   )rE   rI   s     r5   addressable_datazArrayImpl.addressable_data  s>     ,))+++<r7   Sequence[Shard]c           	         |                                   g }| j        D ]>}|                    t          t	          |          | j        | j        |                     ?|S r@   )r   r   rt   r9   r6   r1   rv   )rE   r  r+   s      r5   addressable_shardszArrayImpl.addressable_shards  s^    
C\ F F	jj{1~~t}dj!DDEEEEJr7   c                z   |                                  rt          d | j                  S 	 t          t          j        | j                  | j                  S # t          j        $ rT}|j        ^}}t          |          t          u r/|                    d          rt          d | j                  cY d }~S  d }~ww xY w)NUNIMPLEMENTED)
is_deletedr   r1   r   from_pjrt_layout_pjrt_layoutxeXlaRuntimeErrorre   typer   
startswith)rE   emsg_s       r5   layoutzArrayImpl.layout
  s      )D$-(((%6t7HIIM# # #   gcA	cc		cnn_==	dDM********s$   +A B:&AB5.B:4B55B:c           	     B   |                                   | j        r| j        S g }d | j        D             }| j        j        D ]\}|                    |j        d          ||j                 }nd}|                    t          || j        | j
        |                     ]|S )zReturns list of all `Shard`s of the Array across all devices.

    The result includes shards that are not addressable by the current process.
    If a `Shard` is not addressable, then its `data` will be `None`.
    c                8    i | ]}t          |          j        |S r^   r   r   s     r5   r   z+ArrayImpl.global_shards.<locals>.<dictcomp>%  s#    FFFA;q>>,aFFFr7   N)r   r  rf  r   r1   r   getr   rt   r9   rv   )rE   r  r   global_darrays        r5   global_shardszArrayImpl.global_shards  s     	  %$$
CFFFFFM, D D		 	 d	3	3	?#HK0	jjx
EBBCCCCJr7   c                p    | j         d S | j         D ]}|                                 d | _         d | _        d S r@   )r   deleter   )rE   bufs     r5   r{  zArrayImpl.delete.  sA    |f|  	jjllllDLDOOOr7   c                P    | j         dS t          d | j         D                       S )NTc              3  >   K   | ]}|                                 V  d S r@   )ri  r   r|  s     r5   r   z'ArrayImpl.is_deleted.<locals>.<genexpr>>  s,      88Cs~~888888r7   )r   anyrL   s    r5   ri  zArrayImpl.is_deleted7  s0    |T 884<888888r7   c                    |                                  r*t          d| j                                         d          d S )Nz"Array has been deleted with shape=.)ri  RuntimeErrorrb   r   rL   s    r5   r   zArrayImpl._check_if_deleted@  sR     I
Gty/B/B/D/D
G
G
GI I II Ir7   c                j    |                                   | j        D ]}|                                 | S r@   )r   r   block_until_ready)rE   r   s     r5   r  zArrayImpl.block_until_readyE  s?    l  Kr7   c                @    t          j        | j        d                   S r   )r%  r0  r   rL   s    r5    _single_device_array_to_np_arrayz*ArrayImpl._single_device_array_to_np_arrayL  s    :dl1o&&&r7   c                D    | j         d                                          d S r   )r   copy_to_host_asyncrL   s    r5   '_copy_single_device_array_to_host_asyncz1ArrayImpl._copy_single_device_array_to_host_asyncP  s     LO&&(((((r7   c                    |                                   | j        \| j        r|                                  d S t	          | j        | j                  D ]&\  }}| j        |                                          %d S d S r@   )r   r   r  r  r|   r1   rv   r   )rE   r   rr  s      r5   r  zArrayImpl.copy_to_host_asyncT  s    		! 44666$T]DJ?? B B$!QQ??AAAA B Br7   znp.asarray(jax.Array))r$  
np.ndarrayc                   |                                   | j        8| j        rI|                                 | _        d| j        j        _        t          t          j        | j                  S | j	        s)t          | j        | j                  st          d          t          | j        | j                  D ]$\  }}| j        |                                          %t          j        | j        | j                  }t          | j        | j                  D ]'\  }}| j        |                                         ||<   (|| _        d| j        j        _        | j        S )NFa%  Fetching value for `jax.Array` that spans non-addressable (non process local) devices is not possible. You can use `jax.experimental.multihost_utils.process_allgather` to print the global array or use `.addressable_shards` method of jax.Array to inspect the addressable (process local) shards.)r   r   r  r  flags	writeabler	   r%  ndarrayr  r   r1   rv   r  r|   r   r  emptyr   )rE   r   rr  	npy_valueinds        r5   r   zArrayImpl._value^  sH    			! 1??AA*/'BJ000 ' 
.t}djII
?
 
 	
 %T]DJ?? B B$!QQ??AAAA(4:tz22i&t}djAA L L&!SaIIKK	#!do(-do%?r7   )F)
rb   r   r1   r   r   r   r   r   r   r   )r-   r<   )r   )r-   r   )NNN)r4  r7  r5  r8  r6  r9  r/  r:  )r-   rA  )r-   rZ  )rI   rS   r-   r,   )r-   rd  )r-   r  );rW   rX   rY   __annotations__r)   rF   r   r]   rv   r   r   r   r1   r:   r   r   r   r   r   r   r   r   r   r   r   r   r   r
  r  r  rM   r  r3  r@  rO  rQ  rS  rU  rW  r4   r^  r`  rc  r[   r\   rf  rs  ry  r{  ri  r   r  r  r  r   annotate_functionr  partialr   r^   r7   r5   r,   r,      sY         > 6;" " " " "$$Q $Q $QL    8   8   8 ! ! 8!   8   8   8  : : :  # # #! ! !% % %    ! ! !& & & &     . . .%0 %0 %0NN N N - - - 8-2 2 2, . . . 8.8 8 8 8
 6:7;>B%)           (   >D D D
 >3 3 3 >4 4  84 >: : :$ $ $ $ L L 8L ^ ^ 8^          8    8( >   >9 9 9I I I
 >   >' ' ' >) ) ) B B B 9X/6MNNN   ON 8  r7   slcrN   rv   c                P    t          d t          | |          D                       S )Nc              3  l   K   | ]/\  }}t          |t                    |j        p||j        pd z
  V  0dS )r   N)r   r   stopstart)r   ru   dims      r5   r   z(_get_shape_from_index.<locals>.<genexpr>  s[        
!S	Au		v}A&     r7   )r   r&   )r  rv   s     r5   _get_shape_from_indexr    s:    	  S%((   
 
 r7   __hash____array_priority__r  Sharding | Layoutdata_callback#Callable[[Index | None], ArrayLike]c                  
 t          |t                    r|j        ndt          t                    rt	          d|           t          |t                    r|j        n|}t          |t                    s"t	          d| dt          |                     dfd	|j        rTt          |j
        j                  } t          d          ft          |           z            gt          |          z  }nE|                    |           
t          
                                          }
fd
|D             }|d         }|j        }|                    |           }t%          j        | |          }t)          ||||           t          |t*                    rg|j        r`|j        rY|j        rR|j        j        t1          |          k    r5|j        j        t5          j        t          |          d||          k    r|S t9          j        |j        t8          j                  r8t?          j         ||          }	|j        j!        "                    |||	d          S 6fd|D             }t?          j         ||          }	t+          |||	d          S t          |t*                    r:t          |#                                          dk    rt?          j         ||          }t5          j$        ||||          S )a  Returns a ``jax.Array`` via data fetched from ``data_callback``.

  ``data_callback`` is used to fetch the data for each addressable shard of the
  returned ``jax.Array``. This function must return concrete arrays, meaning that
  ``make_array_from_callback`` has limited compatibility with JAX transformations
  like :func:`jit` or :func:`vmap`.

  Args:
    shape : Shape of the ``jax.Array``.
    sharding: A ``Sharding`` instance which describes how the ``jax.Array`` is
      laid out across devices.
    data_callback : Callback that takes indices into the global array value as
      input and returns the corresponding data of the global array value.
      The data can be returned as any array-like object, e.g. a ``numpy.ndarray``.

  Returns:
    A ``jax.Array`` via data fetched from ``data_callback``.

  Examples:

    >>> import math
    >>> from jax.sharding import Mesh
    >>> from jax.sharding import PartitionSpec as P
    >>> import numpy as np
    ...
    >>> input_shape = (8, 8)
    >>> global_input_data = np.arange(math.prod(input_shape)).reshape(input_shape)
    >>> global_mesh = Mesh(np.array(jax.devices()).reshape(2, 4), ('x', 'y'))
    >>> inp_sharding = jax.sharding.NamedSharding(global_mesh, P('x', 'y'))
    ...
    >>> def cb(index):
    ...  return global_input_data[index]
    ...
    >>> arr = jax.make_array_from_callback(input_shape, inp_sharding, cb)
    >>> arr.addressable_data(0).shape
    (4, 2)
  Nz{`DeviceLocalLayout.AUTO` cannot be used in place of a device-local layout when calling `jax.make_array_from_callback`. Got z6sharding should be an instance of `jax.sharding`. Got z	 of type rI   Index | Noner-   ArrayImpl | np.ndarrayc                    | J  |           }t          |t          j                  rt          j        d          t          j        |          S )NzFjax.make_array_from_callback cannot be called within a traced context.)r   r   Tracerr   UnexpectedTracerErrorr   canonicalize_dtype)rI   rr  s     r5   get_dataz*make_array_from_callback.<locals>.get_data  sa     eA!T[!! (  
 !!$$$r7   c                2    g | ]} |                   S r^   r^   )r   r:   device_to_index_mapr  s     r5   r   z,make_array_from_callback.<locals>.<listcomp>  s6       28$V,--  r7   r   )r   rb   r1   Tr   c                J    g | ]}t          t          |                     S r^   )r   r   )r   r   dlls     r5   r   z,make_array_from_callback.<locals>.<listcomp>  s,    EEEvc/2233EEEr7   r0   )rI   r  r-   r  )%r   r   device_local_layoutr   r   r1   r   rn  r  r   r2   addressable_device_listr   r3   ro   r   r   r   r   ShapedArrayr   r,   r   _device_assignmentr   rs  r   _maybe_get_default_layoutr   
issubdtypeextendedr   ra   _rulesmake_sharded_arrayr4   batched_device_put)rv   r1   r  r4   per_device_valuesfirst_valuer   r   rb   r   r  r  r  s     `       @@@r5   make_array_from_callbackr    sy   T )38V(D(DN$$$#Z   P
	ODL	O 	OP P P #-Xv">">LXH(	Hh	'	' #
	" 	" 	"h	" 	"# # #% % % % % % ! 	81IJJG!5;;.3u::"=>>?#g,,N"BB5II&++--..G    <C   "!$+$.''...		%	0	0$1#	    i(( 

 

& 
) 

1U7^^
C
C1)&h*?*?xQUVVW Wtz6?33 ^-w77F://h$ 0    	_EEEEWEEEG^-w77FT8Vt<<<<Y'' CC0C0C0E0E,F,F,J,J '8'BB		 x1BG	L	LLr7   
local_datar  r;   Shape | Nonec                   j         }|,t          | |          }|J d|v rt          d|d          nd|v rt          d|d          g t          t	          j         |                    D ]Z\  }\  }}                    ||k               ||k    r3t          | ||          }||k    rt          d|d| d| d	|d	          [|                     |          }t          t          |
                                                    }	|	J t          |	|          d
 |D             |
                                D ]=}
|
J t          |
          D ]'\  }}|                             |j        pd           (>t          t          |                    D ]'}t          t!          |                             |<   (t#          j        d          fd            dfd}t'          || |          S )a/  Creates distributed tensor using the data available in process.

  This function is a common special case of `make_array_from_callback`. It
  assumes that the data is available in the process and takes care of the
  index wrangling.

  The most common case is when the sharding is sharded across the batch
  dimension and each host just loads its corresponding sub-batch. This function
  supports more general cases as well, such as mixed multi-host and multi-axis
  replication and sharding but you would need to compute the size and the
  contents of process-local data correctly to satisfy the sharding constraints.

  In particular, if any two hosts are replicas, host_local_data should be
  identical as well.

  The global_shape is optional. If not provided it will be be inferred from
  the local_data and sharding, under the assumption that
  each host represents only their own data for uniform sharding. If sharding
  is non-uniform, (see note below) an exception will be raised.

  Setting global_shape explicitly allows for finer grain control and works with
  non-uniform shardings. Each dimension of global_shape must either match
  host_local_data, or match the inferred global shape of the sharding (in which
  case it is equivalent to setting it to None, but is more explicit).

  For example if dimension `i` is fully sharded then this size would be
  `per_device_shape[i] * jax.local_device_count()`.  Each device will be mapped
  into local slice of `local_data` array. For example, if given process
  addresses slices (8, 12) and  (24, 28), then these slices will be mapped
  into (0, 4) and (4, 8) of the `local_data`.

  For each dimension where global_shapes matches local_shape, each device
  will lookup the slice in the local_data. For example if
  global_shape == local_data.shape, the local data is assumed to be the
  actual target array that will be sharded into device.

  If global_shape is the same as local_data.shape, then the data must
  be the same across all hosts.

  Examples:
    >>> from jax.sharding import PartitionSpec as P
    >>> mesh_rows = 2
    >>> mesh_cols =  jax.device_count() // 2
    ...
    >>> mesh = jax.sharding.Mesh(np.array(jax.devices()).reshape(mesh_rows, mesh_cols), ('x', 'y'))

    >>> sharding = jax.sharding.NamedSharding(mesh, P(('x', 'y'),))
    >>> rows_per_device = 2
    >>> feature_length = 32
    >>> per_device_shape = (rows_per_device, feature_length)
    >>> per_host_shape = (rows_per_device * len(mesh.local_devices), feature_length)
    >>> per_host_generator = lambda : np.arange(np.prod(per_host_shape)).reshape(per_host_shape)
    >>> per_host_data = per_host_generator()  # replace with your own per-host data pipeline that outputs numpy arrays
    >>> global_shape = (rows_per_device * len(sharding.device_set), ) + per_device_shape[1:]
    >>> output_global_array = jax.make_array_from_process_local_data(sharding, per_host_data, global_shape)
    ...
    >>> assert output_global_array.addressable_data(0).shape == per_device_shape
    >>> assert output_global_array.shape == global_shape

  NB: While most shardings are uniform, It is possible to design am exotic
  sharding mesh where each process's  devices will be arranged in a non-grid
  like pattern in some dimensions, or for indices to overlap non-trivially.
  Such sharding is called "non-uniform" in those dimensions. In that case,
  the global shape along those directions must match local shape as there is
  no meaningful way to represent all needed
  per-process data in non-overlapping fashion. For example for global_shape 4x4
  if sharding looks like this:

      0123
      2103
      4675
      4567

  with 4 processes, containing devices (0,1), (2, 3), (4, 5), (6, 7) respectively.
  Then the data for each host look like

      xx..    ..xx     ....    ....
      .xx.    x..x     ....    ....
      ....    ....     x..x    .xx.
      ....    ....     xx..    ..xx

  the sharding is uniform on rows (each host requires either rows 1-2, or rows 3-4)
  and non-uniform on columns (hosts require overlapping but not matching
  set of columns). Thus local data must have the shape 2x4 or 4x4
  for all hosts, even though each  host can potentially fit into 2x2 shape.
  In this case user must provide global_shape explicitly and for
  local_shape=(2, 4), potentially valid global shapes are (2, 4) and (4, 4).

  On the other hand for sharding:

      0213   x.x.  .x.x.  ....  ....
      0213   x.x.  .x.x.  ....  ....
      4657   ....  ....   .x.x  x.x.
      4657   ....  ....   .x.x  x.x.

  for local_shape=(2, 2) this function can accept a choice of 2x2, 2x4, 4x2
  and 4x4 global shapes. Setting global_shape to None, is equivalent to
  setting it to (4, 4) in this case.

  Args:
    sharding: sharding of the global tensor.
    host_local_data: data on the host to be placed on local devices. Each
      dimension should either match global_shape, or match
      num_addressable_indices(dim).
    global_shape: the target shape of the global tensor. If None,
      will infer from host_local_data and sharding.

  Returns:
    Tensor that will have sharding=sharding and of shape global_shape.
  Nz{Unable to compute global_shape due to non-uniform sharding. Specify global shape directly. Partially computed global_shape=r  zglobal_shape=z" has Nones. This is not supported.z^Invalid host data, each dimension should match either global or process shape. In dimension i=z, the process data has zelements. Process addresses z elements and global_shape=c                    g | ]}g S r^   r^   )r   rr  s     r5   r   z6make_array_from_process_local_data.<locals>.<listcomp>  s    )C)C)C")C)C)Cr7   r   rk   )maxsizec                    |                               |pd          |          z  }||          z   }t          ||          S r   )rI   r   )r   r  endr   slices_for_each_dims      r5   local_slicez7make_array_from_process_local_data.<locals>.local_slice  sH      "((!44{1~EE
+a.
 Cr7   rI   r  r-   r$   c                n    | J fdt          |           D             }t          |                   S )Nc              3  T   K   | ]"\  }}|         r|n ||j                   V  #d S r@   )r  )r   r   r  full_dimr  s      r5   r   zAmake_array_from_process_local_data.<locals>.cb.<locals>.<genexpr>  sV        As {9Asy 9 9     r7   )rq   r   )rI   
data_slicer  r  r  s     r5   cbz.make_array_from_process_local_data.<locals>.cb  sY        &&  J eJ''((r7   )rI   r  r-   r$   )rv   r#   rK   rq   ziprt   r"   ro   nextiterrr   r  r  r  r3   sortedrp   r[   	lru_cacher  )r1   r  r;   local_shaper   data_dim
global_dimprocess_slicerf  shardshard_indexr  r  r  r  r   r  s    `           @@@@r5   "make_array_from_process_local_datar    s   n  +(;??L###|Q@LQ Q Q   
 |
IIII
J
JJ(#,	*
L))$ $ 
 
a	(J OOH
*+++:-h<HHm	(	"	" +,   FN   +8         
 
 	
  ??MM
t&--//00
1
1%				%e\::+)C)Cl)C)C)C'..00 4 4k"""K(( 4 43!##CIN33334\""## A Aa#C(;A(>$?$?@@t$$$     %$) ) ) ) ) ) ) ) 
","	=	==r7   Sequence[basearray.Array]c           	        t          d |D                       r2t          dt          t          t          |                               t          j        | |d         j        d          }t          j	        |j        t          j
                  r#|j        j                            |||d          S t          ||t          t          t                   |          d          S )a  Returns a ``jax.Array`` from a sequence of ``jax.Array``\s each on a single device.
      Every device in input ``sharding``\'s mesh must have an array in ``arrays``\s.

  Args:
    shape : Shape of the output ``jax.Array``. This conveys information already included with
      ``sharding`` and ``arrays`` and serves as a double check.
    sharding: Sharding: A global Sharding instance which describes how the output jax.Array is laid out across devices.
    arrays: Sequence of ``jax.Array``\s that are each single device addressable. ``len(arrays)``
      must equal ``len(sharding.addressable_devices)`` and the shape of each array must be the same. For multiprocess code,
      each process will call with a different ``arrays`` argument that corresponds to that processes' data.
      These arrays are commonly created via ``jax.device_put``.

  Returns:
    A global ``jax.Array``, sharded as ``sharding``, with shape equal to ``shape``, and with per-device
      contents matching ``arrays``.

  Examples:

    >>> import math
    >>> from jax.sharding import Mesh
    >>> from jax.sharding import PartitionSpec as P
    >>> import numpy as np
    ...
    >>> mesh_rows = 2
    >>> mesh_cols =  jax.device_count() // 2
    ...
    >>> global_shape = (8, 8)
    >>> mesh = Mesh(np.array(jax.devices()).reshape(mesh_rows, mesh_cols), ('x', 'y'))
    >>> sharding = jax.sharding.NamedSharding(mesh, P('x', 'y'))
    >>> inp_data = np.arange(math.prod(global_shape)).reshape(global_shape)
    ...
    >>> arrays = [
    ...    jax.device_put(inp_data[index], d)
    ...        for d, index in sharding.addressable_devices_indices_map(global_shape).items()]
    ...
    >>> arr = jax.make_array_from_single_device_arrays(global_shape, sharding, arrays)
    >>> assert arr.shape == (8,8) # arr.shape is (8,8) regardless of jax.device_count()

  For cases where you have a local array and want to convert it to a global
  jax.Array, use ``jax.make_array_from_process_local_data``.
  c              3  J   K   | ]}t          |t          j                  V  d S r@   )r   r   r  )r   rX  s     r5   r   z7make_array_from_single_device_arrays.<locals>.<genexpr>  s.      88#C	%	%888888r7   z`jax.make_array_from_single_device_arrays requires a list of concrete arrays as input. got types r   F)r   Tr  )r  rK   rp   maprn  r   r  r   r   r  r  r  r  r,   r	   r   )rv   r1   r   rb   s       r5   $make_array_from_single_device_arraysr    s    \ 	8888888 A
	@'*3tV+<+<'='=	@ 	@A A A 
	%E	B	B	B$tz6?33 @://h:> 0 @ @ @ 
44(;V#D#D!
# 
# 
# #r7   c                    	 t          j        | j                  S # t          $ rA}dt	          |          v r*t          d| j                                                   | d }~ww xY w)Nz9Fetching value for `jax.Array` that spans non-addressablezClosing over jax.Array that spans non-addressable (non process local) devices is not allowed. Please pass such arrays as arguments to the function. Got jax.Array: )r   ir_constantr   r  r   rb   r   )valrp  s     r5   _array_mlir_constant_handlerr    s    

CJ'''	 
 
 
 Cc!ffLLE.1h.@.@.B.BE EF F LMM 

s    
A&<A!!A&rX  r   r  8tuple[tuple[int, ...], tuple[int, ...], tuple[int, ...]]c                   dg| j         z  }t          | j                  }g }t          |t                    r|n|f}t          |          D ]\  }}t          |t                    r#|||<   |dz   ||<   |                    |           =|t          d          k    rQt          |t                    s
J |            t          |j	        t                    s
J |            t          |j
        t                    s
J |            |j	        ||<   |j
        ||<   t	          |          t	          |          t	          |          fS )z2Returns start_indices, limit_indices, removed_dimsr   r0   N)r   r   rv   r   r   rq   rS   rt   r   r  r  )rX  r  start_indiceslimit_indicesremoved_dims	tuple_idxr  sub_idxs           r5   as_slice_indicesr    sK    #.-sy//-,U++7cc#)	** ( (lc7'3 ("mC"Q;mC#	E$KK		''00000s++44W444c**33G333"=mC"<mC	}		u]33U<5H5H	HHr7   c                     t           fd|D                       \  }}}|j        r gt          |          z  }n                     |||          }t	          j                   }t          j        ||||          S )Nc              3  8   K   | ]}t          |          V  d S r@   )r  )r   r  r   s     r5   r   z%shard_device_array.<locals>.<genexpr>+  s?       63 63#&q#63 63 63 63 63 63r7   )r'   r  r3   _multi_slicer   shaped_abstractifyr   r  )	r   r4   r  r1   r  r  r  shardsrb   s	   `        r5   shard_device_arrayr  *  s    /5 63 63 63 63*163 63 63 03 03,-! HS3w<<FF^^M=,GGF		$Q	'	'$		 x	A	AAr7   c                   t          t                    }d | j        D             }t          | j                            | j                                                            }t          ||          D ]-\  }}|t          |                   
                    |           .g }t          ||          D ]\  }}	|t          |                   }
|
s&t          j        |g| j        gd          d         c S |
D ]2}|                                |	hk    r|
                    |            n3|
                    |           t          j        | j        |||          S )Nc                    g | ]	}|j         
S r^   )r=   r  s     r5   r   z8shard_sharded_device_array_slow_path.<locals>.<listcomp>7  s    	3	3	3s#(	3	3	3r7   F)canonicalizer   )r   r   rf  r   r1   rP   rv   rr   r&   r!   rt   r   
shard_argsr   r4   r  rb   )r   r4   r  r1   
candidatesbufsarr_indicesr|  r  r:   candidates_lists              r5   $shard_sharded_device_array_slow_pathr  5  sh   4  *	3	3a2	3	3	3$aj44QW==DDFFGG+4-- . .hc3|C  !((----	$gw//  kc6 c!2!23O L _hZ!(%HHHKKKK   	6(	"	"C 
# kk#		 4	A	AAr7   c                    |                      |                                          }|                     |                                          }|t          |          t          |          k    fS r@   )ro   rr   r   )src_shardingrv   dst_shardingsrc_indicesdst_indicess        r5   _sharding_indices_and_eqr  P  s`    <<UCCJJLL+<<UCCJJLL+	eK((E+,>,>>	>>r7   c           	     p   g }g g g g f\  }}}}t          t          | |                    D ]N\  }\  }}	|                                 t          |j        |j        |	          \  }
}|j        s'|r|                    |           Zt          d          |	j	        }|rw|                    d            |                    |           |                    t          |                     |                    |	           |                    |           t          j        |j                  r'|                    t          |||
|	                     )|                    t          |||
|	                     Pt          j        |||          }t          ||          D ]\  }}||         J |||<   |S )Nz5Cannot reshard an input that is not fully addressable)rq   r&   r   r  r1   rv   r  rt   NotImplementedErrorr   r   r   r  r  r  xc+batched_copy_array_to_devices_with_sharding)xs	shardingsresultsbatch_xs
batch_devsbatch_shardingsbatch_indicesr   r   r1   r  same_indicesr4   	copy_outscopy_outs                  r5   _array_shard_argr  W  s   '9;RR6(J#HR$;$;<< Q Qa!X4	
AGX' 'G\! Q	 Eq!CE E 	E 7g	 Qt$w--(((x(((Q-aj99 Q)!WgxHHIIII0GWhOO	Q 	Q 	Q 	Q <
O- -)mY77  ka1:GAJJ	.r7   c                      j         t          j        k    r fdS t          j         j         t          j                  r! j         j                             ||          S t          j         ||d          S )Nc                L    t          j        j        t          j                  S r@   r%  zerosrv   r   float0)rr  global_avals    r5   <lambda>z._array_global_result_handler.<locals>.<lambda>  s    RXk/?? r7   Tr   )	r   r   r  r  r  r  global_sharded_result_handlerr   array_result_handler)r  out_shardingr   s   `  r5   _array_global_result_handlerr    s    &-''?????{(&/:: .#AA\9. . .		 <94
 
 
 r7   c                      j         t          j        k    r fdS t          j         j         t          j                  r! j         j                             ||          S t          j         |dd          S )Nc                L    t          j        j        t          j                  S r@   r  )rr  rb   s    r5   r  z-_array_local_result_handler.<locals>.<lambda>  s    RXdj&-88 r7   Tr   )	r   r   r  r  r  r  local_sharded_result_handlerr   r  )rb   r1   r  s   `  r5   _array_local_result_handlerr    s    	Z6=  88888tz6?33 !:99h! ! !		 
H4
 
 
 r7   c                6    t          d | D             |          S )Nc                    g | ]	}|j         
S r^   )_buf)r   r   s     r5   r   z$_token_shard_arg.<locals>.<listcomp>  s    ...a16...r7   )r  )r  r  s     r5   _token_shard_argr    s!    	..2...		:	::r7   c                H    t          t          j        ||          fd}|S )Nc                 <     | i |}t          j        |          S r@   )r   Token)re   kwargsout_bufarray_handlers      r5   wrapperz-_token_global_result_handler.<locals>.wrapper  s'    mT,V,,G:gr7   )r  r   token_shaped_array)r  r  r   r&  r%  s       @r5   _token_global_result_handlerr(    s<    .
|Y8 8-     
.r7   )r+   r,   r-   r.   )r   r   r1   r   rb   r   r   r<   )r  rN   rv   r<   r-   r<   )rv   r<   r1   r  r  r  r-   r,   r@   )r1   r   r  r  r;   r  r-   r,   )rv   r<   r1   r   r   r  r-   r,   )rX  r   r  rN   r-   r  )j
__future__r   collectionsr   collections.abcr   r   enumr[   r   operatorr   typingr   r   r	   jax._srcr
   r   r   r   r   r   r   r   r   r   r   jax._src.interpretersr   r   r   jax._src.layoutr   r   r   jax._src.libr   r   r   rl  jax._src.shardingr   jax._src.sharding_implsr   r   r    r!   r"   r#   jax._src.typingr$   r%   jax._src.utilr&   r'   r(   r)   r*   numpyr%  r   rS   r<   r.   r   rN   PRNGKeyArrayr6   r9   rj   r|   r   r   Arrayr,   r  setattrr  r  r  canonical_concrete_avalpytype_aval_mappings
attrgetteridentitycanonicalize_dtype_handlers_shaped_abstractify_handlersregisterr  register_constant_handlerr  r  r  r  r  shard_arg_handlersr  global_result_handlersr  ConcreteArrayr  local_result_handlersr  r"  r(  AbstractTokenr^   r7   r5   <module>rH     s   # " " " " " # # # # # # . . . . . . . .           + + + + + + + + + + $ $ $ $ $ $                                                             & & & & & & & & & & & & % % % % % % A A A A A A A A A A ) ) ) ) ) ) , , , , , , & & & & & &Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y 4 3 3 3 3 3 3 3 P P P P P P P P P P P P P P     	c3h	eSj   0 0 0 0 0 0 0 0f   5111	 	 21	 5111	> 	> 21	>   ,S S S S S	 S S Sr  5)mmBL)))44)    	:t $ $ $ 	' - - -sM sM sM sMr "&l> l> l> l> l>^8# 8# 8# 8#v (7'N ) $&3bmF&;&;  #-1] 	 *3@2=3H3H %i 0 	   # # #
 
 
  y*F G G GI I I I2B B BB B B6 5111? ? 21?$ $ $N &6 	 "   1M D, -2N D. /   0K 4+ ,1L 4- .
; ; ;&6 
 #   3O D. / / /r7   