
    uki!                       d dl mZ d dlmZ d dlZd dlZd dlmZ d dlZ	d dl
mZ d dl
mZ d dlmZ eej                   cZZej$                  Zej&                  Zej(                  Z e       Zej,                  Zej.                  Zeeef   Zej2                  ZddZd	 Zee_        ee_        eeee eeef   d
f   f   Z!	 	 	 	 ddZ"	 	 	 	 ddZ#	 	 d	 ddZ$y)    )annotations)SequenceN)Union)config)util)pmap_libc                   t        |      t        | j                        k(  sJ || j                  f       g }g }t        | j                        D ]O  \  }}||   }t        |t              r|j                  t        d      g       8t        |t              rQ||j                  k(  sJ | d|j                          |j                  t        |             |j                  |       t        |t              rt        j                  |j                        }t        ||      \  }}	|	r
J |||f       |j                  t        |      D 
cg c]  }
t        |
|z  |
dz   |z         c}
       |j                  |j                         ;t!        j"                  |       R t%        j&                  t        j                  |      gt$        j(                        }t        t+        j,                  |       D ]
  \  }
}|||
<    |j/                  |      }t        |      }| j0                  D cg c]  }t        |t2              s|j4                  ! }}t7        |      t7        t        |            k(  rt        |      |k(  sJ t9        d | j0                  D              }t+        j:                  d      t=        |      }}| j0                  D cg c]4  }t        |t>              rtA        |      nt        |      tA        |      z   6 }}t%        jB                  |||jD                  z         jG                  |      S c c}
w c c}w c c}w )a  Returns NumPy-style indices corresponding to a sharding spec.

  Args:
    shape: The shape of the logical array being sharded.

  Returns:
    An ndarray with the same shape as the logical mesh (as derived form
    `mesh_mapping`). Each entry is a NumPy-style index selecting the subset of
    the data array to be placed on a corresponding device. The indices can be
    ints, slice objects with step=1, or tuples of those.
  Nz !=    )dtypec              3  V   K   | ]!  }t        |t              s|j                   # y wN)
isinstance
Replicatedreplicas).0as     R/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/jax/_src/sharding_specs.py	<genexpr>z)_sharding_spec_indices.<locals>.<genexpr>m   s     [qAzAZ

[s   ))r   )$lensharding	enumerater   
NoShardingappendslice	UnstackedsizerangeChunkedmathprodchunksdivmodextendr   assert_unreachablenpemptyobject_	itertoolsproductreshapemesh_mappingShardedAxisaxissettuplecountiterr   nextbroadcast_toshape	transpose)selfr4   axis_indicesshard_indices_shapedimr   	axis_sizetotal_chunks
shard_sizeraggedishard_indicesidxsnum_sharded_dimr   sharded_dim_permreplica_sizesreplica_dimsharded_dimperms                       r   _sharding_spec_indicesrG   :   s    
Us4==)	)AE4==+AA	)(*, / (mc8c
I(J'5;-( 
Hi	((--'JI;d8==/)JJ'%	*+  +	Hg	&YYx/l!)\:j&7)\377Z$),$79  !Z!a%:1EF 9 :  1
h'%(0 ((DII&9:;2::N-9,,l;< gaM!''(;<- +,/&*&7&7V:a;UaffVV

3u_'=#>
>

?
24 3 [D,=,=[[-&__Q/6F1G{+ $$
&  *!Z8${

m
tK0
01 
&$ 
& //-9L9L)L
MYt_59" W
&s   	L9
,L>L>9Mc                <    d| j                    d| j                   dS )NzShardingSpec(z, )r   r+   )r6   s    r   _sharding_spec_reprrK   u   s"    r$*;*;)<A	>>    .c                J    t        |j                  |       j                        S )a  Returns numpy-style indices corresponding to a sharding spec.

  Each index describes a shard of the array. The order of the indices is the
  same as the device_buffers of a Array sharded using PmapSharding (i.e. the
  data is laid out row-major).

  Args:
    shape: The shape of the logical array being sharded.
    spec: Describes how the array is sharded and how the shards are assigned to
      the logical mesh.

  Returns:
    A tuple of length equal to the size of the mesh (inferred as the product of
    sharded dimension sizes and all replication factors).  Each element is an
    int, a slice object with step=1, or a tuple thereof, to be treated as an
    index into the full logical array.
  )r/   indicesflat)r4   specs     r   spec_to_indicesrQ      s    & 
t||E"''	((rL   c                  
 t        | |      \  }}|rJ t        t        gt        |      z  d      }|dk(  rdnt	        |      f}|t        d |j                  d| D              
d
fd}t        j                  j                  r,t        j                  |j                  |t        |g            }	n*t        j                  |j                  |t        |            }	t        |	t        j                   t#        
      g|t%        ||j&                                    S t        |j                  t	        |      f|z   |j&                  z         S )az  Sharding spec for arguments or results of a pmap.
  Args:
    nrep: number of local XLA replicas (product of local axis sizes)
    axis_size: local axis size for outer pmap
    sharded_aval: the aval of the value inside the outer pmap, an instance of
      a ShapedArray.
    map_axis: the axis along which the value is mapped in the outer pmap
  Returns:
    A ShardingSpec.
   rJ   r
   Nc              3  >   K   | ]  }t        |t                 y wr   )r   r   )r   ss     r   r   z%pmap_sharding_spec.<locals>.<genexpr>   s     [AjJ77[s   c                v    t        | t              r'| j                  k\  rt        | j                  dz         S | S Nr
   )r   r,   r-   )r   sharded_in_axiss    r   shift_sharded_axisz.pmap_sharding_spec.<locals>.shift_sharded_axis   s0    	A{	#/(A166A:&&hrL   )r   MeshDimAssignment)r"   ShardingSpec_UNSHARDED_INSTANCEr   r   sumr   r   pmap_no_rank_reductionvaluer   tuple_updater   tuple_insertr   r(   chainr,   mapr+   )nrepr:   sharded_shapemap_axisreplication_factorr=   pspecmaybe_replicaterY   r   rX   s             @r   pmap_sharding_specrj      s=     &dI6f
!4 5M8J J$&(%,1B
CU8V7X/[PYQYAZ[[O $$**""
..(GYK$8:h ""
..(Ii$8:h??'
(/
 %"4"4
578 8 ~~y)+o=@R@RRT TrL   c                    |Pt         j                  j                  rt        j                  | |d      }nt        j
                  | |      }|| |   }n|J | }t        ||||      S rW   )r   r^   r_   r   r`   tuple_deleterj   )r4   rE   sharded_dim_sizere   s       r   create_pmap_sharding_specrn      sw    $$**''{A>m''{;m{+'''M	,.>'
) )rL   )r4   tuple[int, ...]returnz
np.ndarray)r4   Sequence[int]rP   r[   rp   ztuple[Index, ...])re   rq   rf   
int | Nonerp   r[   )r   N)r4   ro   rE   intrm   rr   )%
__future__r   collections.abcr   r(   r   typingr   numpyr%   jax._srcr   r   jax._src.libr   rc   safe_map
unsafe_mapr   r   r   r\   r,   r   rZ   r[   rG   rK   rN   __repr__rs   r   r/   IndexrQ   rj   rn   rS   rL   r   <module>r~      s  < # $       !t}}
C  



	 l ""  
+z12 $$9v? . +  	c5%c5j 13 6778)&)+<),'T!+'T0<'TT JK=A)0:)rL   