
    uki                       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m	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, d dl-m.Z. d dl/m0Z0m1Z1m2Z2 d dl3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z; d dl<m=Z=m>Z>m?Z?m@Z@ d dlAmBZBmCZCmDZDmEZEmFZF d dlGZHeBeIcZIZJeKeLdf   ZMe*j                  ZNeKeOdf   ZPeZQdCd!ZR G d" d#      ZSd$ ZT eFd%d&'      d(        ZU eFd%d&'      d)        ZV	 	 	 	 	 	 	 	 dDd*ZW G d+ d ej                        ZYes  eDe*j                        eY      ZYdEd,ZZ	 	 	 	 	 	 dFd-Z[ e\eYd.d        e\eYd/d0       	 dG	 	 	 	 	 	 	 	 	 dHd1Z]	 dGd2Z^	 dG	 	 	 	 	 	 	 dId3Z_dd4	 	 	 	 	 	 	 	 	 dJd5Z`d6 ej                  eY<   d7 Zbebej                  eY<   d8 Zd e j                  eYed       ej                  j                  rej                  j                  eY       dKd9Zjd: Zkd; Zl eFd%d&'      d<        Zm eFd%d&'      d=        Znd> Zoeoe!j                  eY<   d? Zqeqe!j                  ej                  <   d@ Ztete!j                  ej                  <   dA Zveve!j                  ej                  <   dB Zxexe!j                  ej                  <   y)L    )annotations)defaultdict)CallableSequenceN)partial)AnyTYPE_CHECKINGcast)api)	basearray)config)core)dispatch)dtypes)errors)literals)profiler)util)
xla_bridge)are_hlo_shardings_equal)mlir)pxla)
AutoLayoutFormatLayout)_jax)jaxlib_extension_version)
xla_client)empty_concrete_mesh)Sharding)broadcast_prefixtree_flattentree_unflatten)PmapShardingSingleDeviceShardingNamedShardingdevice_replica_id_maphashed_indexnum_addressable_indiceslocal_to_global_shape_internal_use_concrete_mesh)	ArrayLikeDLDeviceType	DTypeLikeExtendedDType)safe_zipunzip3use_cpp_classuse_cpp_methodcache.	ArrayImplc                    | j                   j                  }t        |      dk7  rt        dt        |       d      |d   S )N   zpWhen making an array from single-device arrays the input arrays must have one shard each. An argument array had z
 shard(s).r   )sharding_internal_device_listlen
ValueError)adevicess     I/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/jax/_src/array.py_get_devicer?   >   sN    JJ,,'\Q
	669'l^:	OP P 
    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y)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.
  Nc                <    || _         || _        || _        || _        y N)_device	_sharding_global_shape_data)selfdevicer8   global_shapedatas        r>   __init__zShard.__init__S   s    DLDN%DDJr@   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=))rJ   index
replica_idrL   r;   rI   s    r>   __repr__zShard.__repr__Z   ss    @dkk_HTZZL A OO,GDII;aA B @T[[O7499+Q??@s   69 &A"!A"c                    	 | j                   j                  } || j                        | j
                     }|J |S # t        $ r t        d| j                    d      d w xY w)Nz(Cannot calculate indices from sharding: z<. Please create a device to index mapping for your sharding.)rF   devices_indices_mapAttributeErrorr;   rG   rJ   )rI   device_indices_map_fnrP   s      r>   rP   zShard.indexa   s{    ?"nn@@
 "$"4"45dkkBEL  ?A..) *44 5:>??s	   = $A!c                \    t        | j                  | j                        | j                     S rD   )r'   rF   rG   rJ   rR   s    r>   rQ   zShard.replica_idm   s"     1C1CDT[[QQr@   c                    | j                   S rD   )rE   rR   s    r>   rJ   zShard.deviceq   s    <<r@   c                    | j                   S rD   )rH   rR   s    r>   rL   z
Shard.datau   s    ::r@   rD   )rJ   Devicer8   r    rK   ShaperL   zNone | ArrayImpl | PRNGKeyArray)returnIndex)r]   int)__name__
__module____qualname____doc__rM   rS   	functoolscached_propertyrP   rQ   propertyrJ   rL    r@   r>   rB   rB   G   s}    	 8<4@ 	 	 R R    r@   rB   c                     | | }|j                  |       t        j                  |      } |j                  j                  di ||_        |S )z=Method to reconstruct a device array from a serialized state.rg   )__setstate__r   
device_putavalupdate)funargs	arr_state
aval_statenp_value	jnp_values         r>   _reconstruct_arrayrs   z   sH    $Z(
	"nnX&)(9>>((6:6).	r@      F)max_sizetrace_context_in_keyc                    | j                  |      }t               }g }t        |j                               D ]9  \  }}t	        |      }||vs|j                  |       |j                  ||f       ; |S rD   )addressable_devices_indices_mapset	enumeratevaluesr(   addappend)sshapemap_seen_h_indiceslarray_indexrP   h_indexs           r>   _cached_index_calcr      su    	
	*	*5	1$5.!%dkkm4 %k55!Gn$!hhU#$	%
 
(r@   c                L   t        j                         dk(  ryt        | j                  |      j	                         D ch c]  }t        |       c}      }t        | j                  |      j	                         D ch c]  }t        |       c}      }||k(  S c c}w c c}w )Nr7   F)r   process_countr:   rU   r{   r(   rx   )r~   r   vnum_unique_indicesnum_addressable_unique_indicess        r>    _process_has_full_value_in_mcjaxr      s     1$ ! 5 5e < C C EF1|AFH#& ! A A% H O O QR1|AR$T 	=	== GRs   B>B!c                    |j                   }| D ]m  }|j                   |k7  rt        d|j                    d| d|       |j                  |k7  s@t        d| d|j                   d|j                          d|        y)	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)dtyper;   r   	str_short)arraysr8   rk   expected_shapeexpected_dtypedbs         r>   /_validate_shape_and_dtype_for_per_device_arraysr      s     ::. b	xx>!
+n%5]2$H  
xx>!!.!1 2  "z)=^^ohZ9 r@   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       	 dA	 	 	 	 	 dBd       Zd ZedCd       Zed        Z	ed        Z
ed        Zed        Zed        Zed        ZedDd       Zd Zd Zd Zd Zd Zd Zd Zd ZdEdZd Zd  Zd! Zd" ZedDd#       Zd$ Zd% ZedDd&       Z dFd(Z!d'd'd'd'd)	 	 	 	 	 dGd*Z"dHd+Z#d, Z$ e       d-        Z%e e       d.               Z& e       d/        Z'dId0Z(ed1        Z)ed2        Z*dJd3Z+e,jZ                  dKd4       Z.ed5        Z/edKd6       Z0 e       d7        Z1 e       d8        Z2d9 Z3 e       d:        Z4 e       dLd;       Z5 e       d<        Z6e7jp                  d=        Z9e e,jt                  e7jp                  d>?      dMd@              Z;y')Nr5   core.ShapedArrayrk   r    rF   zlist[ArrayImpl]_arraysbool
_committed_skip_checksznp.ndarray | None
_npy_valuec                   || _         || _        || _        d | _        |D cg c]  }|j                  d    }}|rt
        j                  j                  r'| j                  || j                  | j                         }|| _        y c c}w Nr   )	rk   rF   r   r   r   r   enable_checksvalue_check_and_rearrange)rI   rk   r8   r   	committedr   r<   s          r>   rM   zArrayImpl.__init__   sv     DIDNDODO$*+qaiil+F+ 6//55((KfDL ,s   Bc                   |D ci c]  }t        |      j                  | }}|j                  }t        |      t        |      k7  r#t	        dt        |       dt        |             t        |j                               }|D ch c]  }|j                   }	}t        |      t        |      k7  r0|D cg c]  }t        |      j                   }
}t	        d|
       ||	z  }|r-|	|z
  }||	z
  }d}|r	|d| dz  }|r	|d| dz  }t	        |      t        ||||j                  |j                        	       |j                  }|D cg c]  }||j                      c}S c c}w c c}w c c}w c c}w )
Nz	Expected zW per-device arrays (this is how many devices are addressable by the sharding), but got zsWhen making an array from single-device arrays, the input arrays must be from distinct devices, but got device IDs 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.)r8   rk   r   )r?   idaddressable_devicesr:   r;   ry   keysr   shard_shaper   _addressable_device_assignment)rI   r   r8   rk   r   device_id_to_bufferaddressable_devarray_device_idsdaddressable_device_idsbuffer_device_idsdiffdev_in_sharding_not_in_arraysdev_in_arrays_not_in_shardingerr_msgaddressable_darJ   s                    r>   r   zArrayImpl._check_and_rearrange   s   <BCb;r?--r1CC22O
6{c/**c/*+ ,V   
 .3356,;<qadd<<
F+8>?";r?--?? "# # 44D&<?O&O#&69O&O#
K 	&12O1P QA A 	B	&9:W9X Y< < 	=w3++DJJ7	 <<N9GHv		*HHW D =?> Is   E(E-7E2E7c                .    | j                   j                  S rD   )rk   r   rR   s    r>   r   zArrayImpl.shape       99??r@   c                .    | j                   j                  S rD   )rk   r   rR   s    r>   r   zArrayImpl.dtype  r   r@   c                ,    t        | j                        S rD   )r:   r   rR   s    r>   ndimzArrayImpl.ndim  s    tzz?r@   c                @    t        j                  | j                        S rD   )mathprodr   rR   s    r>   sizezArrayImpl.size	  s    99TZZ  r@   c                    | j                   S rD   )rF   rR   s    r>   r8   zArrayImpl.sharding  s    >>r@   c                    | j                          t        | j                  t              r"t	        | j                  j
                        d   S | j                  S r   )_check_if_deleted
isinstancer8   r%   list
device_setrR   s    r>   rJ   zArrayImpl.device  sA    $--!56$--**+A..==r@   c                .    | j                   j                  S rD   )rk   	weak_typerR   s    r>   r   zArrayImpl.weak_type  s    99r@   c                    | j                   S rD   )r   rR   s    r>   r   zArrayImpl.committed  s    ??r@   c                \    	 | j                   d   S # t        $ r}t        d      |d }~ww xY w)Nr   zlen() of unsized object)r   
IndexError	TypeError)rI   errs     r>   __len__zArrayImpl.__len__   s3    :ZZ] :/0c9:s    	+&+c                V    t        j                  |        t        | j                        S rD   )r   check_bool_conversionr   _valuerR   s    r>   __bool__zArrayImpl.__bool__&  s    t$r@   c                `    t        j                  |        | j                  j                         S rD   )r   check_scalar_conversionr   	__float__rR   s    r>   r   zArrayImpl.__float__*  s#      &;;  ""r@   c                `    t        j                  |        | j                  j                         S rD   )r   r   r   __int__rR   s    r>   r   zArrayImpl.__int__.  s#      &;;  r@   c                `    t        j                  |        | j                  j                         S rD   )r   r   r   __complex__rR   s    r>   r   zArrayImpl.__complex__2  s#      &;;""$$r@   c                V    t        j                  |        t        | j                        S rD   )r   check_integer_conversionhexr   rR   s    r>   __hex__zArrayImpl.__hex__6      !!$'t{{r@   c                V    t        j                  |        t        | j                        S rD   )r   r   octr   rR   s    r>   __oct__zArrayImpl.__oct__:  r   r@   c                j    t        j                  |        t        j                  | j                        S rD   )r   r   oprP   r   rR   s    r>   	__index__zArrayImpl.__index__>  s#    !!$'88DKK  r@   c                8    | j                   j                  |      S rD   )r   tobytes)rI   orders     r>   r   zArrayImpl.tobytesB  s    ;;u%%r@   c                6    | j                   j                         S rD   )r   tolistrR   s    r>   r   zArrayImpl.tolistE  s    ;;r@   c                ~    | j                   dk(  rt        | j                  d   |      S t        | j                  |      S )Nr   rg   )r   formatr   )rI   format_specs     r>   
__format__zArrayImpl.__format__H  s3    yyA~DKKO[11DKK--r@   c                   ddl m} ddlm} | j	                          t        | j                  t              rt        j                  j                  rWt        |t              r|n|f}t        d |D              t        d       ft        | j                        t        |      z
  z  z   }nkt        |t              s*|ft        d       ft        | j                        dz
  z  z   }n1|t        d       ft        | j                        t        |      z
  z  z   }t        | j                  j                  | j                        j!                               }	 |j#                  |      }|| j&                  |   }t)        t+        |            }	t        j                  j                  r.t        d t-              D              }
|j/                  ||
      }t1        |j2                  |	|gdd	
      S |j5                  | |      S # t$        $ r d }Y w xY w)Nr   )lax)indexingc              3  `   K   | ]&  }t        |t              rt        ||d z   d      n| ( yw)r7   N)r   r_   slice).0is     r>   	<genexpr>z(ArrayImpl.__getitem__.<locals>.<genexpr>X  s0      
CDZ3%7E!QUD!Q>
s   ,.r7   c              3  H   K   | ]  \  }}t        |t              s|  y wrD   )r   r_   )r   r   xs      r>   r   z(ArrayImpl.__getitem__.<locals>.<genexpr>m  s     KTQ
1c8JqKs   "")
dimensionsFTr   r   )jax._src.laxr   jax._src.numpyr   r   r   r8   r$   r   pmap_no_rank_reductionr   tupler   r:   r   rU   r{   rP   r;   r   r%   r?   rz   squeezer5   rk   rewriting_take)rI   idxr   r   cidxpadded_cidxindicesarr_idxoutr8   dimss              r>   __getitem__zArrayImpl.__getitem__O  s    '$--.		&	&	,	, e,s3& 
HL
 
4[Nc$**oD	9:; #u%%+3tzz?Q3F!GG+uT{nDJJ#c(0JKK+dmm77

CJJLMg--, 
	ll7#'C(89((.. KYt_KK$CD1#HHhTK 	K ""4--!  s   G< <H
	H
c                     j                   dk(  rt        d       j                  s j                  sJ t	        j
                   j                        s j                  rd  j                  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  J   K   | ]  }|j                         D ]  }|   y wrD   )_unstack)r   chunksls      r>   r   z%ArrayImpl.__iter__.<locals>.<genexpr>|  s#     Qu@PQ"QQs   !#d   c              3  (   K   | ]	  }|     y wrD   rg   r   r   rI   s     r>   r   z%ArrayImpl.__iter__.<locals>.<genexpr>~  s     6AQ6s   c              3  b   K   | ]&  }t        j                  j                  |          ( y wrD   )r   rj   r   r	  s     r>   r   z%ArrayImpl.__iter__.<locals>.<genexpr>  s"     M1t{{1~.Ms   ,/)r   r   is_fully_replicatedis_fully_addressabler   is_single_device_shardingr8   _chunk_iterr   r$   ranger   rR   s   `r>   __iter__zArrayImpl.__iter__v  s    yyA~233%%)B)BBB		+	+DMM	:d>V>VQ 0 0 5QQdmm\26tzz!}!566 Ndjjm8LMMr@   c                .    | j                   j                  S rD   )r8   r  rR   s    r>   r  zArrayImpl.is_fully_replicated  s    ==,,,r@   c                `   d}| j                   1| j                   j                  rd| j                  j                   d}nd| j                  j                   }t	        | j
                  t              r@| j
                  j                  j                  r d| j                   d| d| j
                   dS | j                  s| j                  rt        j                         d   }| j                  d	k(  rd
| j                   }nJ| j
                  j                  sd| j                   }n$t        j                   | j"                  |dd|      }t%        |      |j'                  d      z
  dz   }d}|t%        |      z   dz   |kD  rdt%        |      z  }| | d| | dS | d| j                   d| dS )NzArray(zdtype=z, weak_type=TruezArray(shape=z, z, sharding=rO   	linewidthr   z
[], shape=zshape=,)prefixsuffix	separatormax_line_width
r7       )rk   r   r   namer   r8   r&   spec	unreducedr   r  r  npget_printoptionsr   has_addressable_devicesarray2stringr   r:   rfind)rI   r  	dtype_str
line_widthr~   last_line_lenseps          r>   rS   zArrayImpl.__repr__  s   Fyy!4!44::??++;<i4::??+,i$--/DMM4F4F4P4PDJJ<r)KaPP		"	"d&>&>&&(5j	a%}}44TZZL!OODKKs&*:G!fqwwt},q0mc	Y	'!	+j	8CKxs!C51--xvdjj\I;a88r@   c                    t        | j                  t              r+| j                  j                  j                  rt        |       S | j                  s| j                  rt        | j                        S t        |       S rD   )
r   r8   r&   r  r  reprr  r  strr   rR   s    r>   __str__zArrayImpl.__str__  sV    $--/DMM4F4F4P4P$Z		"	"d&>&>$Zr@   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.
    )r8   r  rR   s    r>   r  zArrayImpl.is_fully_addressable  s     ==---r@   Nc                V    |i nd|i}t        j                  | j                  fd|i|S )Ncopyr   )r  asarrayr   )rI   r   contextr.  kwdss        r>   	__array__zArrayImpl.__array__  s.    2FD>D::dkk77$77r@   )streammax_version	dl_devicer.  c                   ddl m} | j                  j                  }t	        |      dkD  rt        dt	        |       d      |\  } || |||||      S )Nr   )	to_dlpackr7   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.)r3  r4  
src_devicer5  r.  )jax._src.dlpackr7  r8   r   r:   BufferError)rI   r3  r4  r5  r.  r7  r   rJ   s           r>   
__dlpack__zArrayImpl.__dlpack__  so     *))J
:	558_4E F	 
 GFT&!, &(	   r@   c                   t        | j                        dk7  rt        d      ddlm} | j                         dk(  r|j                  dfS | j                         dk(  rut        |       j                  j                  }d|v r|j                  }nd|v r|j                  }nt        d	|       t        |       j                  }|t        d
      ||fS t        d| j                                )Nr7   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: )r:   r   r:  r9  r-   platformkDLCPUr?   clientplatform_versionkDLCUDAkDLROCMlocal_hardware_id)rI   r-   rD  dl_device_typerG  s        r>   __dlpack_device__zArrayImpl.__dlpack_device__  s    
4<<AIJJ,}}%  !##	E	!$T*11BB	#	#%--%%%--A,-/ 0 	0 &d+==		"IJJ... 
L]]_ r@   c                    | j                   j                         \  }}}d| j                  j                  i}t        ||||ffS )Nr   )r   
__reduce__rk   r   rs   )rI   rm   rn   ro   rp   s        r>   rK  zArrayImpl.__reduce__  sC    ;;113Cytyy223JdIz BCCr@   c                    t        | j                        dk7  rt        d      | j                  d   j                         S )Nr7   z?unsafe_buffer_pointer() is supported only for unsharded arrays.r   )r:   r   r;   unsafe_buffer_pointerrR   s    r>   rM  zArrayImpl.unsafe_buffer_pointer  s<    
4<<A " # #<<?0022r@   c                z    t        | j                        dk7  rt        d      | j                  d   j                  S )Nr7   zB__cuda_array_interface__() is supported only for unsharded arrays.r   )r:   r   r;   __cuda_array_interface__rR   s    r>   rO  z"ArrayImpl.__cuda_array_interface__  s;     4<<A + , ,<<?333r@   c                r    | j                   d   }|j                         }|| j                  j                  z  S )z>Returns the total global on-device size of the array in bytes.r   )r   on_device_size_in_bytesr8   num_devices)rI   arrper_shard_sizes      r>   rQ  z!ArrayImpl.on_device_size_in_bytes  s4     ,,q/C002NDMM5555r@   c                N    | j                          | j                  j                  S rD   )r   r8   r   rR   s    r>   r=   zArrayImpl.devices  s    ==###r@   c                    t        d      )NzBarr.device_buffer has been deprecated. Use arr.addressable_data(0)rV   rR   s    r>   device_bufferzArrayImpl.device_buffer  s    
JL Lr@   c                    t        d      )NzTarr.device_buffers has been deprecated. Use [x.data for x in arr.addressable_shards]rW  rR   s    r>   device_bufferszArrayImpl.device_buffers  s    
\^ ^r@   c                x    | j                          | j                  r| j                         S | j                  |   S rD   )r   r  _fully_replicated_shardr   )rI   rP   s     r>   addressable_datazArrayImpl.addressable_data  s5    ))++<<r@   c           	         | j                          g }| j                  D ]<  }|j                  t        t	        |      | j
                  | j                  |             > |S rD   )r   r   r}   rB   r?   r8   r   )rI   r   r<   s      r>   addressable_shardszArrayImpl.addressable_shards  sP    
C\\ F	jj{1~t}}djj!DEFJr@   c                   | j                         rt        d | j                        S 	 t        t        j                  | j
                        | j                        S # t        j                  $ rQ}|j                  ^}}t        |      t        u r,|j                  d      rt        d | j                        cY d }~S  d }~ww xY w)NUNIMPLEMENTED)
is_deletedr   r8   r   from_pjrt_layout_pjrt_layoutr   JaxRuntimeErrorrn   typer*  
startswith)rI   emsg_s       r>   r   zArrayImpl.format'  s     D$--((F++D,=,=>MM# # gcA	cc	cnn_=dDMM**s$   2A B?.AB:3B?9B::B?c           	        | j                          | j                  r| j                  S g }| j                  D ci c]  }t	        |      j
                  | }}| j                  j                  D ]a  }|j                  |j
                  d      ||j
                     }nd}|j                  t        || j                  | j                  |             c |S c c}w )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`.
    N)r   r  r_  r   r?   r   r8   r   getr}   rB   r   )rI   r   r<   r   global_darrays         r>   global_shardszArrayImpl.global_shards6  s     	  $$$
C9=FA;q>,,a/FFMM,, D		 	 d	3	?#HKK0	jjx

EBCD J Gs   Cc                |    | j                   y | j                   D ]  }|j                           d | _         d | _        y rD   )r   deleter   )rI   bufs     r>   rq  zArrayImpl.deleteK  s9    |||| 	jjlDLDOr@   c                T    | j                   yt        d | j                   D              S )NTc              3  <   K   | ]  }|j                           y wrD   )rb  )r   rr  s     r>   r   z'ArrayImpl.is_deleted.<locals>.<genexpr>[  s     8Cs~~8s   )r   anyrR   s    r>   rb  zArrayImpl.is_deletedT  s&    || 84<<888r@   c                r    | j                         r't        d| j                  j                          d      y )Nz"Array has been deleted with shape=.)rb  RuntimeErrorrk   r   rR   s    r>   r   zArrayImpl._check_if_deleted]  s:    .tyy/B/B/D.EQ
GI I r@   c                h    | j                          | j                  D ]  }|j                           | S rD   )r   r   block_until_ready)rI   r   s     r>   rz  zArrayImpl.block_until_readyb  s2    ll Kr@   c                     y rD   rg   rR   s    r>   )_single_device_array_to_np_array_did_copyz3ArrayImpl._single_device_array_to_np_array_did_copyi  s    r@   c                >    | j                   d   j                          y r   )r   copy_to_host_asyncrR   s    r>   '_copy_single_device_array_to_host_asyncz1ArrayImpl._copy_single_device_array_to_host_asyncm  s    LLO&&(r@   c                .   | j                          | j                  y| j                  r'| j                  j                  r| j                          y t        | j                  | j                        D ]"  \  }}| j                  |   j                          $ y y rD   )	r   r   r  r8   r!  r  r   r   r   )rI   r   rj  s      r>   r~  zArrayImpl.copy_to_host_asyncq  sy    		!	!dmm&K&K446$T]]DJJ? B$!QQ??AB	 r@   znp.asarray(jax.Array))r  c                   | j                          | j                  d| j                  rE| j                  j                  r/| j                         \  }}d|j                  _        |r|| _        |S | j                  s+t        | j                  | j                        st        d      t        | j                  | j                        D ]"  \  }}| j                  |   j                          $ t        j                   | j                  | j"                        }t        | j                  | j                        D ](  \  }}| j                  |   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  r8   r!  r|  flags	writeabler  r   r   rx  r   r   r  r  emptyr   )rI   	npy_valuedid_copyr   rj  inds         r>   r   zArrayImpl._value{  sG    			!	!dmm&K&K"LLN	8$)	!%$/
 ''.t}}djjI?
 	
 %T]]DJJ? B$!QQ??AB ((4::tzz2i&t}}djjA X&!S LLOUUW	#X!do(-doo%??r@   )F)
rk   r   r8   r    r   zSequence[ArrayImpl]r   r   r   r   )r]   r\   )r]   r   )C)NNN)r3  zint | Any | Noner4  ztuple[int, int] | Noner5  ztuple[DLDeviceType, int] | Noner.  zbool | None)r]   ztuple[enum.Enum, int])r]   zset[Device])rP   r_   r]   r5   )r]   zSequence[Shard])r]   ztuple[np.ndarray, bool])r]   
np.ndarray)<r`   ra   rb   __annotations__r3   rM   r   rf   r   r   r   r   r8   rJ   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  rS   r+  r  r2  r;  rI  rK  rM  rO  rQ  r=   rX  rZ  r]  rd   re   r_  r   ro  rq  rb  r   rz  r|  r  r   annotate_functionr~  r   r   rg   r@   r>   r5   r5      s>    6;*.2 &,I\       ! !        :#!%!& .%.NN - -94 . .8
 6:7;>B%) 4 ;  # (>D
 3 3 4  4 6 6$ L L ^ ^      (   9 9I
     ) ) B B 9X//6MN! O !r@   c                :    t        d t        | |      D              S )Nc              3     K   | ]8  \  }}t        |t              r#|j                  xs ||j                  xs d z
   : yw)r   N)r   r   stopstart)r   r~   dims      r>   r   z(_get_shape_from_index.<locals>.<genexpr>  s;      
!S	Au	 	vv}A&s   >A )r   r0   )slcr   s     r>   _get_shape_from_indexr    s#    	 S%( 
 r@   c           	         |"| r| d   j                   }|S t        d| d      t        j                  ||      }| r4| d   j                   |k7  r"t        d| d| d| d   j                    d      |S )Nr   zbIf the Array has no addressable shards, `dtype` must be provided via the `dtype` argument to `jax.z`.zIf `dtype` is provided to `jax.z@`, it must match the dtype of the addressable shards. Got dtype=z and shard dtype=)r   r;   r   !check_and_canonicalize_user_dtype)r   r   fnames      r>   _get_and_check_dtyper    s    
 ]Qiooe 
, ..3WB89 9 44UEBE&)//U*+E7 3227 9!9??#2'( ( 
,r@   __hash____array_priority__r  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                  rKt        |j                  j                        } |t        d      ft        |       z        gt        |      z  }nB|j                  |       }t        |j                               }|D 	cg c]  }	 |||	          }}	t!        ||d      }|j#                  |       }
t%        j&                  t%        j(                  | |      |      }t+        ||
||       d}|rv|d   }t        |t,              ra|j.                  rU|j                  rI|j                  r=|j
                  j0                  t3        |      k(  r|j4                  j                  |k(  r|S t7        j8                  |j:                  t6        j<                        r?t?        j@                  ||      }|j:                  jB                  jE                  |||d	
      S |G|D cg c]  }t        |tG        |             }}t?        j@                  ||      }t-        |||d	
      S t        |t,              r2t        |jI                               dkD  rt?        j@                  ||      }tK        jL                  ||||      S c c}	w c c}w )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``.
    dtype: The dtype of the output ``jax.Array``. If not provided, the dtype of
      the data for the first addressable shard is used. If there are no
      addressable shards, the ``dtype`` argument must be provided.

  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)
  Nzp`Layout.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 c                   | J  |       }t        |t        j                        rt        j                  d      t        j                  |      }t        |t        j                  t        j                  t        j                  f      r8t        j                  t        j                  ||j                        d      }|S t        |t              r:t        j                  t        j                  |t        j                         d      }|S )NzFjax.make_array_from_callback cannot be called within a traced context.r   Fr   )r   r   Tracerr   UnexpectedTracerErrorr   canonicalize_valuer   TypedInt
TypedFloatTypedComplexTypedNdArrayr  r/  r   r   bool_)rP   rdata_callbacks     r>   get_dataz*make_array_from_callback.<locals>.get_data  s     eA!T[[!(( 
 	!!!$A!h'')<)<++- .




1AGG <
Na H 
At	




1BHH =
OaHr@   make_array_from_callback)r   rk   r8   r   Tr   r7   )rP   Index | Noner]   z.ArrayImpl | literals.TypedNdArray | np.ndarray)'r   r   layoutr   r   r8   r    rf  r  r   r9   addressable_device_listr   r:   rx   r   r  r   r   update_aval_with_shardingShapedArrayr   r5   r   _device_assignmentr   r   r   
issubdtyper   extendedr   rj   _rulesmake_sharded_arrayr%   r=   r   batched_device_put)r   r8   r  r   dllr  r=   per_device_valuesdevice_to_index_maprJ   r   rk   first_valuer   r   s     `            r>   r  r    s   \ &h7T#Z 
	DDL:	OP P #-Xv">XH(	Hh	'

@
 Kh 	"# #5, !!811IIJG!5;.3u:"=>?#g,N"BB5I&++-.G<C28$V,-   :<%''..		'	'
ue$h
0$ 2#	 +#A&K;	*""((++  33uW~E%%,tzz6??3^^-w7F:://h$ 0   	_=DEvc/23EGE^^-w7FT8Vt<<Y'C0C0C0E,F,J '8'B		 	 x1BG	LL[F Fs   L
-Lc           
        t        |      \  }}t        | |      }t        t        t        j
                  d      |      }t        ||d       }t        j                         dk(  rXt        ||      D ]3  \  }}|	||j                  k7  st        d| d|j                   d       t	        j                  ||       S t        |||      D 	
cg c]  \  }	}}
t        |	||
       }}}	}
t        ||      S c c}
}}	w )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 an 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 array.
    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 array. If None,
      will infer from local_data and sharding.

  Returns:
    Tensor that will have sharding=sharding and of shape global_shape.
  "make_array_from_process_local_datac                .    | d u xs t        | t              S rD   )r   r   r   s    r>   <lambda>z4make_array_from_process_local_data.<locals>.<lambda>  s    T	9Z5%9 r@   )is_leafr7   zWhen calling `make_array_from_process_local_data` on a single process, global_shape should be None or equal to local_data.shape.Got global_shape=z and local_data.shape=rw  )r"   r!   mapr   r   pspec_to_shardingr   r   zipr   r;   rj   _array_from_process_local_datar#   )r8   
local_datarK   local_data_flattreedefsharding_flatglobal_shape_flatr~   r   rL   r   r   s               r>   r  r  R  s#   h **5/7"8Z8-c##%IJ- 'J9; 1$%7 
1	
1<223 5!!"	,
 	

 >>*h//  #?MCTU	W 	WT1e 
(a	7 	W# 	W		%%	Ws   C6c                     j                   }|#t        ||      }|J d |v r"t        d|d      d |v rt        d|d      g t        t	         j                   |            D ]L  \  }\  }}j                  ||k(         ||k7  s#t        |||      }||k7  s6t        d| d| d| d|d	       |j                  |      }t        t        |j                                     }	|	J t        |	|      |D 
cg c]  }
g  c}
|j                         D ];  }|J t        |      D ]'  \  }}|   j                  |j                  xs d	       ) = t        t        |            D ]  }t        t!        |               |<    t#        j$                  d
      fd       d fd}t'        |||      S c c}
w )Nz{Unable to compute global_shape due to non-uniform sharding. Specify global shape directly. Partially computed global_shape=rw  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 z, the process data has z elements. Process addresses z elements and global_shape=r   rt   )maxsizec                h    |    j                  |xs d      |    z  }||    z   }t        ||      S r   )rP   r   )r   r  endr   slices_for_each_dims      r>   local_slicez3_array_from_process_local_data.<locals>.local_slice  sB      "((!4{1~EE
+a.
 Cr@   c                R    | J fdt        |       D        }t        |         S )Nc              3  X   K   | ]!  \  }}|   r|n ||j                          # y wrD   )r  )r   r   r  full_dimr  s      r>   r   z=_array_from_process_local_data.<locals>.cb.<locals>.<genexpr>  s3      As {Asyy 99s   '*)rz   r   )rP   
data_slicer  r  r  s     r>   cbz*_array_from_process_local_data.<locals>.cb  s5    &J eJ'((r@   )rP   r  r]   r,   )r   r*   r;   rz   r  r}   r)   rx   nextiterr{   r  r  r  r:   sortedry   rd   	lru_cacher  )r  r8   rK   local_shaper   data_dim
global_dimprocess_slicer_  shardrj  shard_indexr  r  r  r  r   r  s   `             @@@@r>   r  r    s2   
   +(;?L###|N@LaQ  |
&HI
JJ(#,	*

L)$ 
a	(J OOH
*+:-h<Hm	(	"++,#-DXJ O++8/ :oQ 
 	

  ??M
t&--/0
1%			%e\:+6B)C")C'..0 4k"""K( 43!##CIIN344 \"# Aa#C(;A(>$?@A t$ %) 
","	==1 *Ds   	Gr  c          
        t        |t              rt        ||d      }t        j                  t        j
                  | |d      |      }t        j                  |j                  t        j                        r)|j                  j                  j                  |||d      S t        |t              rt        |      n|}	 t        ||t        t        t           |      d      S # t         $ ra t        |t              st!        dt#        |       d      t%        d |D              r%t'        d	t)        t+        t"        |                    w xY w)
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: `list` or `tuple` 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``.
    dtype: The dtype of the output ``jax.Array``. If not provided, the dtype of the first array in
      ``arrays`` is used. If ``arrays`` is empty, the ``dtype`` argument must be provided.

  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``.
  $make_array_from_single_device_arraysFr  Tr  z\jax.make_array_from_single_device_arrays `arrays` argument must be a list or tuple, but got rw  c              3  P   K   | ]  }t        |t        j                           y wrD   )r   r   r  )r   rS  s     r>   r   z7make_array_from_single_device_arrays.<locals>.<genexpr>_  s     
:C:c4;;'
:s   $&zdjax.make_array_from_single_device_arrays requires a list of concrete arrays as input, but got types )r   r   r  r   r  r  r   r  r   r  r  r  r   r   r5   r
   r   rf  ru  r;   ry   r  )r   r8   r   r   rk   s        r>   r  r    sE   ^ ! =?E
 
	'	'
ueu5x
A$tzz6??3:://h:> 0 @ @%fe44<&&
T8T(9*=v%F"$ $	 	
fd# Cfa) * * 
:6
::--0T61B-C,DFG G 
	
s   ?#C# #A*Ec                    | S rD   rg   r  s    r>   r  r  e  s    ! r@   c                V    t        j                  | j                  | j                        S rD   )r   r  rk   r8   rR   s    r>   _get_aval_arrayr  g  s    		'	'		4==	AAr@   c                    	 t        j                  | j                        S # t        $ r:}dt	        |      v r't        d| j
                  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   rx  r*  rk   r   )valrk   rh  s      r>   _array_mlir_constant_handlerr  l  st    

CJJ''	 
 Cc!fL..1hh.@.@.B-CEF LMM 

s   ! 	A$5AA$c                J   dg| j                   z  }t        | j                        }g }t        |t              r|n|f}t        |      D ]  \  }}t        |t              r|||<   |dz   ||<   |j                  |       5|t        d      k(  rDt        |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   r7   N)r   r   r   r   r   rz   r_   r}   r   r  r  )rS  r   start_indiceslimit_indicesremoved_dims	tuple_idxr  sub_idxs           r>   as_slice_indicesr    s    #.-syy/-,U+c#)	* (lc7'3"mC"Q;mC#	E$K	'00's+4W4+c*3G3*"==mC"<<mC( 
}	u]3U<5H	HHr@   c                4    t         fd|D              \  }}}|j                  r gt        |      z  }n+t        t              5   j                  |||      }d d d        t        j                         }t        j                  |||      S # 1 sw Y   6xY w)Nc              3  6   K   | ]  }t        |        y wrD   )r  )r   r   r   s     r>   r   z%shard_device_array.<locals>.<genexpr>  s      63#&q#63s   )
r1   r  r:   r+   r   _multi_slicer   shaped_abstractifyr   r  )	r   r=   r   r8   r  r  r  shardsrk   s	   `        r>   shard_device_arrayr    s    /5 63*163 03,-!!S3w<F 
%%8	9 J~~m]LIfJ		 	 	#$		 	 x	AAJ Js   BBc                   t        t              }| j                  D cg c]  }|j                   }}t	        | j
                  j                  | j                        j                               }t        ||      D ]"  \  }}|t        |         j                  |       $ g }t        ||      D ]  \  }}	|t        |         }
|
sEt        j                  |gd gt        j                  j                   g| j"                  gd      d   c S |
D ])  }|j%                         |	hk(  s|j                  |         |j                  |
d           t        j&                  | j(                  |||      S c c}w )NF)canonicalizer   )r   r   r_  rL   r   r8   rU   r   r{   r0   r(   r}   r   
shard_argsxcArrayCopySemanticsREUSE_INPUTr   r=   r  rk   )r   r=   r   r8   
candidatesrr  bufsarr_indicesr   rJ   candidates_lists              r>   $shard_sharded_device_array_slow_pathr    sW   4 *22	3s#((	3$	3ajj44QWW=DDFG+4- .hc3|C !((-. 
$gw/ 'kc6 c!23O__hZ$ 33??@188**/1124 4
  '	6(	"C'
 kk/"%&' 
	 	 4	AA+ 
4s   E/c                    | j                  |      j                         }|j                  |      j                         }t        |      t        |      k(  S rD   )rx   r{   r   )src_shardingdst_shardingr   src_indicesdst_indicess        r>   _fallback_check_via_indicesr    sI    <<UCJJL+<<UCJJL+	{	u[1	11r@   c                    t        | j                  |      |j                  |            }t        | j                  j                        t        |j                  j                        k(  }|xr |S rD   )r   _to_xla_hlo_shardingr:   r9   r  )r  r  r   hlos_eqlen_eqs        r>   _sharding_indices_and_eqr
    sc    #L$E$Ed$K$0$E$Ed$KM'22JJK22JJKL&		Vr@   c           
        t        j                  d       g }g g g g f\  }}}}g }	t        t        | |||            D ]  \  }
\  }}}}|j	                          	 t        |j                  |t        |j                              }|dn|j                  j                  |k(  }|j                  s!|r|r|j                  |       t        d      |j                  j                   }|rj|rh|j                  d        |j                  |       |j                  |       |j                  |       |j                  |
       |	j                  |       |s1|j                  t#        j$                  |t'        ||                   F|j)                  |j                        j+                         }t-        j.                  |j                        r|j                  t1        ||||             |j                  t3        ||||              t        j                  d       t5        j6                  ||||	      }t        ||      D ]  \  }
}||
   J |||
<    |S # t        $ r% t        |j                  ||j                        }Y w xY w)N_array_shard_argTz5Cannot reshard an input that is not fully addressablebatched_copy_array)r   
test_eventrz   r0   r   r
  r8   r:   r   NotImplementedErrorr  r   r  r  r}   r9   r  r   rj   r   rx   r{   r   r  r  r  r  +batched_copy_array_to_devices_with_sharding)xs	shardingslayoutscopy_semanticsresultsbatch_xs
batch_devsbatch_shardingsbatch_indicesbatch_csr   r   r8   r  cssame_shardingsame_layoutr=   r   	copy_outscopy_outs                        r>   r  r    sJ   //$%'9;RR6(J(&/r9g~6'8 #S"a	"!XvrQ.qzz8S\Rm !.$ahhoo.GK!!	;q!CE 	E ..FFg	;t'"x(Qs~~a)ABC::177CJJL--ajj9
..+AwJ
K
..21gwQSE#SJ //&'<<
OX7)mY7 ka1:GAJ 
.M  Q1!**hPmQs   *I*JJc                     j                   t        j                  k(  rM fd}t        dk\  r=t	        j
                         }t        j                  |||d      j                  |      S |S t        j                   j                   t        j                        r' j                   j                  j                   ||      S t        j                   ||d      S )Nc                `    t        j                  j                  t        j                        S rD   r  zerosr   r   float0)r  global_avals    r>   handlerz-_array_global_result_handler.<locals>.handler	  s    XXk''77r@     Tr   )r   r   r$  r   r   physical_avalr  array_result_handlerwrapr  r  r  global_sharded_result_handler)r%  out_shardingr   r&  	phys_avals   `    r>   _array_global_result_handlerr.    s    &--'83&$$[1i$$Y	2688<WF n{((&//:##AA\9. .		 	 <94
 r@   c                     j                   t        j                  k(  rM fd}t        dk\  r=t	        j
                         }t        j                  ||dd      j                  |      S |S t        j                   j                   t        j                        r' j                   j                  j                   ||      S t        j                   |dd      S )Nc                `    t        j                  j                  t        j                        S rD   r"  )r  rk   s    r>   r&  z,_array_local_result_handler.<locals>.handler  s    XXdjj&--00r@   r'  Tr   )r   r   r$  r   r   r(  r  r)  r*  r  r  r  local_sharded_result_handler)rk   r8   r   r&  r-  s   `    r>   _array_local_result_handlerr2    s    	ZZ6== 13&$$T*i$$YD2688<WF ntzz6??3::99h! !		 	 
H4
 r@   c                >   g }t        | ||      D ]  \  }}}|J |j                          t        j                  g t              }t        j                  |      }|j                  }	|j                  t        j                  |||gt        |	      z  |	              |S )Nr  )r0   rz  r  rn  r   r   get_avalr   r}   r   r  r:   )
r  r  r  r  r  r   r8   r  rk   r=   s
             r>   _token_shard_argr5  /  s    '%b)W= 6a6>>
4 A==D55GNN4**hc'l*G5 66 
.r@   c                    t        t        j                         ||      t        dk\  rd }j	                  |      S fd}|S )Nr'  c                ,    t        j                  |       S rD   r   Token)rn  s    r>   wrapperz-_token_global_result_handler.<locals>.wrapperA  s    ZZr@   c                 >     | i |}t        j                  |      S rD   r8  )rn   kwargsout_bufarray_handlers      r>   old_wrapperz1_token_global_result_handler.<locals>.old_wrapperE  s!    t.v.gZZ  r@   )r.  r   get_token_avalr   r*  )r%  r,  r   r:  r?  r>  s        @r>   _token_global_result_handlerrA  =  sH    .
\96-$g&&! r@   )r<   r5   r]   r[   )r   z8Sequence[ArrayImpl | np.ndarray | literals.TypedNdArray]r8   r    rk   r   r   r\   )r  r^   r   r\   r]   r\   )r   z>Sequence[basearray.Array | np.ndarray | literals.TypedNdArray]r   z DTypeLike | ExtendedDType | Noner  r*  rD   )
r   r\   r8   zSharding | Formatr  z#Callable[[Index | None], ArrayLike]r   DTypeLike | Noner]   r5   )r  r  r8   r    rK   zShape | Noner]   r5   )
r   r\   r8   r    r   zSequence[basearray.Array]r   rB  r]   r5   )rS  r   r   r^   r]   z8tuple[tuple[int, ...], tuple[int, ...], tuple[int, ...]])z
__future__r   collectionsr   collections.abcr   r   enumrd   r   r   operatorr   typingr   r	   r
   jax._srcr   r   r   r   r   r   r   r   r   r   r   jax._src.op_shardingsr   jax._src.interpretersr   r   jax._src.layoutr   r   r   jax._src.libr   r   r   r  jax._src.meshr   jax._src.shardingr    jax._src.tree_utilr!   r"   r#   jax._src.sharding_implsr$   r%   r&   r'   r(   r)   r*   r+   jax._src.typingr,   r-   r.   r/   jax._src.utilr0   r1   r2   r3   r4   numpyr  r  
unsafe_zipr   r_   r\   r[   r   r^   PRNGKeyArrayr?   rB   rs   r   r   r   Arrayr5   r  r  setattrr  r  r  r  canonicalize_value_handlersr  pytype_aval_mappingsr  register_constant_handleruse_simplified_jaxpr_constantsr   literalable_typesr|   r  r  r  r  r
  r  shard_arg_handlersr.  global_result_handlersr  r2  local_result_handlersr5  r9  rA  AbstractTokenrg   r@   r>   <module>rb     s   # # .      + +            9 & & 6 6  1 ) - & M M8 8 8 N M P P CZc3h	eSj0 0f 51	 2	 51	> 2	>D  	,k	 kb )mBLL))4)J+ . 	:t $ 	' - #CMCM-CM6CM CM (1CMR J&\ "&:>:>&.:>:>*3:>~ #H
H
$H
.GH
H
 H
T 1< " "9 -B'6  ) $
   y*F G	((..Y'I2BB4 512 22
 51 21d &6  	 "  1M  D,, -  0K  4++ ,

 '7  

 # 3O  D.. /r@   