
    ^j=                         d Z ddlZddlmZmZ ddlmZ ddlmZ ddl	m
Z
mZ ddlZddlmZmZmZmZmZmZmZmZmZmZmZmZ  ed	       G d
 d             Z ed	       G d dee                Zy)zj
Definition of CuTe inspired Layouts for DeviceMesh internal bookkeeping and functions to manipulate them
    N)IteratorSequence)	dataclass)product)NoReturnoverload)as_tuplecoalesce
complementcompositionflattenIntTupleis_intis_tupleLayoutmake_layoutmatch_structuresuffix_productT)frozenc                      e Zd ZU dZeedf   ed<   eedf   ed<   ddededz  ddfdZde	fdZ
d	ede	fd
ZdefdZdefdZddZdedd fdZdee   fdZdedeee      fdZdefdZdefdZedeeeef      fd       Zy)_FlatLayouta  
    A canonical CuTe layout for a single dimension of a DeviceMesh

    Utility class for representing an integer layout by borrowing ideas from CuTe Layout Algebra.
    See https://docs.nvidia.com/cutlass/media/docs/cpp/cute/02_layout_algebra.html for more details.

    Each layout is represented as a list of sizes and strides. We use it as a way for mechanical bookkeeping
    of the integers such as ranks in a SPMD mesh, and the transformation on top of it.

    Lots of methods of layout like coalesce, composition, complement, etc. are borrowed from pycute.
    https://github.com/NVIDIA/cutlass/blob/6dd13d42784ee5bfa232d2441e6b9a021c5c6290/python/pycute/layout.py#L137,L257

    Note this is a CuTe-inspired layout, because CuTe uses co-lexicographic way in linearization while PyTorch
    is using lexicographic. So even though the CuTe documentation can still be referenced, the implementation will be
    different from that of PyCute's.

    This layout is _not_ itself subdivided into multiple dimensions. It might
    internally sometimes use multidimensional tuple to represent "irregular"
    layouts (e.g., flattening non-adjacent dims), but this should be considered
    an opaque implementation detail.

    This class guarantees that all equivalent layouts are encoded as the same
    normalized representation, and thus compare equal. This is achieved by
    flattening and coalescing compatible adjacent dimensions (which includes
    removing all dimensions of size 1).

    .shapestrideNreturnc                    t        |      s"t        |      st        dt        |             ||n
t	        |      }t        |      s"t        |      st        dt        |             t        ||      st        d| d| d      t        t        ||            }t        |j                        }t        |j                        }|dk(  r	|dk(  rd}d}t        j                  | d	|       t        j                  | d
|       y )Nz"shape must be a tuple or int, got z#stride must be a tuple or int, got zsizes z and strides z don't match)   )r    r   r   )r   r   	TypeErrortyper   r   
ValueErrorr
   r   r   r   r   object__setattr__)selfr   r   coalesced_layout
flat_shapeflat_strides         i/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/torch/distributed/_mesh_layout.py__init__z_FlatLayout.__init__=   s    ve}@eNOO!->%3HvA$v,PQQuf-veWM&NOO#F5&$9:-334
.556 +"5JK 	4*54;7    c                     t        d      )NzWYou should never need to know the length of the internal representation of a FlatLayoutRuntimeErrorr#   s    r'   __len__z_FlatLayout.__len__T   s    e
 	
r)   ic                     t        d      )NzOYou should never need to index into the internal representation of a FlatLayoutr+   r#   r/   s     r'   __getitem__z_FlatLayout.__getitem__Y   s    ]
 	
r)   c                 r    | j                   st        dd      S t        | j                   | j                        S )Nr   r   )r   r   r   r-   s    r'   	to_pycutez_FlatLayout.to_pycute^   s*    zz!Q<djj$++..r)   c                 @    t        j                  | j                        S N)mathprodr   r-   s    r'   numelz_FlatLayout.numelc   s    yy$$r)   c                    t        | j                         |j                               }t        t        |j                        t        |j
                              D cg c]  \  }}t        ||       }}}t        |      S c c}}w )u  
        By-dimension composition allows one layout to "select from" or "filter through" another layout.
        Think of it as function composition: (self ∘ layout)(input) = self(layout(input))
        between two layouts. This function is a wrapper of pycute's composition.

        Mental model about how to understand the composition logic:
        - The LEFT layout (self) defines the "output space" - what indices are possible
        - The RIGHT layout (layout parameter) acts as a "selector" - which specific indices to pick
        - The composition only generates indices that the left layout could originally produce,
          but the right layout determines which indices to be picked.
        - The stride of the composition layout will not be smaller than the stride of the right layout,
          because when picking the indices the composition will at least follow the right layout's stride
          to move forward.

        Example:
          self = (6,2):(2,1)      # sizes=(6,2), strides=(2,1)
          layout = (3:2)          # sizes=(3,), stride=(2,)
          self o layout = (3:2)

        Returns:
          Layout being composed.
        )r   r4   zipr	   r   r   r   _MeshLayout)r#   layoutresultr   r   result_axess         r'   r   z_FlatLayout.compositionf   su    . T^^-v/?/?/AB "%Xfll%;Xfmm=T!U
v v&
 
 ;''	
s   B
world_sizec                 v    t        | j                         |      }t        |j                  |j                        S )uG  
        Compute the "complement layout" relative to a given world_size.
        A complement layout fills in the "missing" factor so that: self repeat a layout of complement(self, world_size)
        will get a complete world_size. We use ⊗ to denote the repeat operation.

        Example:
          self = (4:1)   # size=4, stride=1
          world_size = 8
          Then:
            complete needed factor = 8 / 4 = 2
            complement(self, 8) = (2:1)

          Together they form:
            (4:1) ⊗ (2:1) = (4,2):(2,1)
          which has world_size = 4 * 2 = 8, as required.

        In distributed terms, complement() is often used to derive the "other"
        rank grouping when splitting processes into 2D meshes.

        For a visualized explanation, see https://x.com/ezyang/status/1962364978393981433/
        )r   r4   r   r   r   )r#   r@   r>   s      r'   r   z_FlatLayout.complement   s,    , DNN,j96<<77r)   c           
          t        d | j                  D         D cg c](  }t        d t        || j                        D              * c}S c c}w )a  
        This function computes the all ranks specified by the layout staring from zero.

        How it works:
        1. we enumerates every possible coordinate (like a nested for-loop).
        If sizes = (2, 3), we get the following coordinates:
            (0,0), (0,1), (0,2), (1,0), (1,1), (1,2)

        2. For each coordinate, we compute a linear rank index as:
            all_ranks_from_zero = sum(coord[i] * strides[i] for i in range(ndim))

        Example A:
        sizes = (2, 3)        # 2 rows, 3 cols
        strides = (3, 1)        # row-major layout
        coords = (0,0) -> 0*3 + 0*1 = 0
                 (0,1) -> 0*3 + 1*1 = 1
                 (0,2) -> 0*3 + 2*1 = 2
                 (1,0) -> 1*3 + 0*1 = 3
                 (1,1) -> 1*3 + 1*1 = 4
                 (1,2) -> 1*3 + 2*1 = 5
        result = [0, 1, 2, 3, 4, 5]

        Example B:
        sizes = (2, 3)
        strides = (1, 2)        # non-standard / strided layout
        coords = (0,0) -> 0*1 + 0*2 = 0
                 (0,1) -> 0*1 + 1*2 = 2
                 (0,2) -> 0*1 + 2*2 = 4
                 (1,0) -> 1*1 + 0*2 = 1
                 (1,1) -> 1*1 + 1*2 = 3
                 (1,2) -> 1*1 + 2*2 = 5
        result = [0, 2, 4, 1, 3, 5]
        c              3   2   K   | ]  }t        |        y wr6   )range).0ss     r'   	<genexpr>z2_FlatLayout.all_ranks_from_zero.<locals>.<genexpr>   s     "@58"@s   c              3   ,   K   | ]  \  }}||z    y wr6   r   )rE   crF   s      r'   rG   z2_FlatLayout.all_ranks_from_zero.<locals>.<genexpr>   s     :$!QA:s   )r   r   sumr;   r   )r#   coords     r'   all_ranks_from_zeroz_FlatLayout.all_ranks_from_zero   sJ    H !"@TZZ"@A
 :#eT[["9::
 	
 
s   -Ac           	          | j                  |      j                         D cg c]#  }| j                         D cg c]  }||z   	 c}% c}}S c c}w c c}}w )us  
        Build global ranks specified by the layout via two-level ranks composition.

        The nested list forms the Cartesian product of all ranks for one layout and offset
        regarding filling up the world_size with the layout.
        The final global ranks are the addition of these two. The result is a
        list of lists: one sublist per layout. This rank list will be used to build
        the communicator underlying the layout and the given `world_size`.

        Example:
        world_size = 16
        self.size = 4
        self.stride = 1
        ranks = [0, 1, 2, 3]
        offsets = [0, 4, 8, 12]
        result = [
            [0+0, 0+1, 0+2, 0+3],  # → [0, 1, 2, 3]
            [4+0, 4+1, 4+2, 4+3],  # → [4, 5, 6, 7]
            [8+0, 8+1, 8+2, 8+3],  # → [8, 9, 10,11]
            [12+0, 12+1, 12+2, 12+3],  # → [12,13,14,15]
        ]
        )r   rL   )r#   r@   offsetranks       r'   global_ranksz_FlatLayout.global_ranks   sQ    2 //*5IIK
 (,'?'?'ABtVd]B
 	
B
s   AAAAc                 \    t        t        | j                  d            | j                  k(  S )NTreverse)tuplesortedr   r-   s    r'   check_sortedz_FlatLayout.check_sorted   s!    VDKK674;;FFr)   c                     t        | j                        dk  ryt        t        t        | j                  | j                        d       \  t        fdt        t              dz
        D              S )u  
        Check if the layout has any overlap between the ranks it generates. If there is overlap,
        we return False, otherwise True.

        The layout is supposed to be injective i.e, aside from indice 0, indices from each
        dim of the layout must be non-overlapping.

        Example 1 - Valid (no overlap):
        Layout: sizes=(2,3), strides=(6,1)
        - Dim 1: stride=1, span=3*1=3, covers indices [0,1,2]
        - Dim 0: stride=6, span=2*6=12, covers indices [0,6]
        → No overlap since 6 > 3

        Example 2 - Invalid (overlap):
        Layout: sizes=(2,3), strides=(2,1)
        - Dim 1: stride=1, span=3*1=3, covers indices [0,1,2]
        - Dim 0: stride=2, span=2*2=4, covers indices [0,2]
        → Overlap! stride=2 < span=3, so indices [0,2] are duplicated

        Example 3 - Invalid (overlap):
        Layout: sizes=(4,2), strides=(1,1)
        - Dim 1: stride=1, span=4, covers indices [0,1,2,3]
        - Dim 0: stride=1, span=2, covers indices [0,1]
        → Overlap! stride is same for two dims, so indices [0,2] are duplicated

        Returns:
            bool: True if no overlap, False if overlap detected
           TrR   c              3   R   K   | ]  }|   |d z      |d z      z  z  dk(     yw)r   r   Nr   )rE   r/   r   r   s     r'   rG   z/_FlatLayout.check_orthogonal.<locals>.<genexpr>  s<      
 1IAq1u56!;
s   $'r   )lenr   r;   rU   r   allrD   )r#   r   r   s    @@r'   check_orthogonalz_FlatLayout.check_orthogonal   sc    : tzz?QVCTZZ$@$OP 
3v;?+
 
 	
r)   c                 B    t        | j                  | j                        S )z5Iterate over (size, stride) pairs for each dimension.)r;   r   r   r-   s    r'   sizes_and_stridesz_FlatLayout.sizes_and_strides  s     4::t{{++r)   r6   )r=   r<   r   r<   )__name__
__module____qualname____doc__rT   int__annotations__r   r(   r   r.   r2   r   r4   r9   r   r   listrL   rP   boolrV   r\   propertyr   r^   r   r)   r'   r   r      s   8 c?#s(O8h 84 84 8.
 


S 
X 

/6 /
%s %(<8S 8] 82%
T#Y %
N
s 
tDI 
8Gd G#
$ #
J ,8E#s(O#< , ,r)   r   c                      e Zd ZU dZeedf   ed<   dee   ddfdZe		 ddee
df   dee
df   dz  dd fd	       Zde
fd
Zede
defd       Zededd fd       Zde
ez  ddfdZdee   fdZdefdZedee
df   fd       Zde
fdZde
fdZdefdZde
de
dd dd fdZdej6                  dej6                  fdZy)r<   a%  
    A multi-dimensional structure consisting of a series of dimension-less layouts

    This class represents the layout of a full DeviceMesh, where the overall
    top-level ndim and "logical" shape are well defined, but each individual
    mesh axis is squashed and normalized into a canonical _FlatLayout.

    It only contains methods that need to make use of this multi-dimensional
    structure (i.e., which access the ndim or the top-level sizes). Everything
    else should go on _FlatLayout and accessed by first calling .collapse().

    .axesr   Nc                 D    t         j                  | dt        |             y )Nri   )r!   r"   rT   )r#   ri   s     r'   r(   z_MeshLayout.__init__  s    4t5r)   sizesstridesc                     |t        t        |            }t        |      t        |      k7  r#t        dt        |       dt        |             t	        d t        ||      D              } | |      S )Nz1sizes and strides must have the same length, got z and c              3   >   K   | ]  \  }}t        |f|f        y wr6   )r   )rE   rF   ds      r'   rG   z1_MeshLayout.from_sizes_strides.<locals>.<genexpr>,  s     MA[!t,Ms   )r   r   rZ   r    rT   r;   )clsrk   rl   ri   s       r'   from_sizes_stridesz_MeshLayout.from_sizes_strides"  st     ?nU34Gu:W%CCJ<uUXY`UaTbc  MUG9LMM4yr)   c                 ,    t        | j                        S r6   )rZ   ri   r-   s    r'   r.   z_MeshLayout.__len__/  s    499~r)   r/   c                      y r6   r   r1   s     r'   r2   z_MeshLayout.__getitem__2  s    25r)   c                      y r6   r   r1   s     r'   r2   z_MeshLayout.__getitem__5  s    69r)   z_FlatLayout | _MeshLayoutc                 p    t        |t              rt        | j                  |         S | j                  |   S r6   )
isinstanceslicer<   ri   r1   s     r'   r2   z_MeshLayout.__getitem__8  s-    atyy|,,yy|r)   c                 ,    t        | j                        S r6   )iterri   r-   s    r'   __iter__z_MeshLayout.__iter__=  s    DIIr)   c                 |    t        | j                        dk(  rt        dd      S t        d | j                  D         S )Nr   r   c              3   <   K   | ]  }|j                           y wr6   )r4   rE   axiss     r'   rG   z(_MeshLayout.to_pycute.<locals>.<genexpr>C  s     D$T^^-D   )rZ   ri   r   r   r-   s    r'   r4   z_MeshLayout.to_pycute@  s3    tyy>Q!Q<D$))DEEr)   c                 :    t        d | j                  D              S )Nc              3   <   K   | ]  }|j                           y wr6   )r9   r}   s     r'   rG   z._MeshLayout.top_level_sizes.<locals>.<genexpr>G  s     8dTZZ\8r   )rT   ri   r-   s    r'   top_level_sizesz_MeshLayout.top_level_sizesE  s    8dii888r)   c                 @    t        j                  | j                        S r6   )r7   r8   r   r-   s    r'   r9   z_MeshLayout.numelI  s    yy--..r)   c                 >    | j                         j                         S r6   )r4   cosizer-   s    r'   r   z_MeshLayout.cosizeL  s    ~~&&((r)   c                     t        d | j                  D              }t        d | j                  D              }t        ||      S )z
        Merge all axes into a single _FlatLayout.

        This is used to "forget" the multi-dimensional structure of this object
        and recover a "flat" (and coalesced) representation.
        c              3   4   K   | ]  }|j                     y wr6   )r   r}   s     r'   rG   z'_MeshLayout.collapse.<locals>.<genexpr>V  s     8dtzz8   c              3   4   K   | ]  }|j                     y wr6   )r   r}   s     r'   rG   z'_MeshLayout.collapse.<locals>.<genexpr>W  s     ::r   )rT   ri   r   )r#   shapesrl   s      r'   collapsez_MeshLayout.collapseO  s9     8dii88:		::67++r)   startendr=   c                 r    t        | j                        }t        |j                        ||| t        |      S )z
        Replace (out-of-place) the start:end slice with the given list of layouts

        Returns the concatenation of self[:start] + layout + self[end:].
        )re   ri   r<   )r#   r   r   r=   new_axess        r'   splicez_MeshLayout.spliceZ  s1     		?"6;;/s8$$r)   rank_mapc                    |j                   dk7  rt        |j                         st        |j                         | j	                         k  rt        | j                         }|j                  |j                               } |j                  |j                  |j                  z   |j                  |j                  z         j                  dg| j                   S )a  
        Leverage layout as an index for mesh tensor that re-maps the indexes after layout
        transformation to actual device ranks.

        With this method, the cute layout serves as the backend of indices bookkeeping for the
        mesh tensor when it comes to flatten, unflatten and slicing operations. The actual mesh
        tensor still represents the actual device assignment and ranks. We need this function
        to specify device allocation and create backend for a mesh. Although any transform of mesh tensors
        can be treated as a view or subset of mesh tensor, we do need to use the actual view or
        sub-tensor for DeviceMesh and its backend creation.

        The shape of the `rank_map` must be 1D and contiguous.

        Examples:

        Case 1 - Consecutive ranks, full world:
            original_mesh_tensor = [[0,1],[2,3]]  # 2x2 mesh, ranks 0-3
            world_size = 4
            layout = Layout(2:2)
            Return: [[0,2],[1,3]]

        Case 2 - Non-consecutive ranks:
            original_mesh_tensor = [[10,20],[30,40]]  # custom rank assignment
            world_size = 4
            layout = Layout(2:2)
            Return: [[[10,30],[20,40]]]

        Args:
            rank_map: The concrete mesh tensor with actual device ranks

        Returns:
            torch.Tensor: A tensor representing the actual device allocation from rank_map
        r   )ndimAssertionErroris_contiguousr9   r   r   r   
as_stridedr   r   reshaper   )r#   r   self_layoutcomplement_layouts       r'   remap_to_tensorz_MeshLayout.remap_to_tensord  s    D ==A  %%'  >>dkkm+  mmo'228>>3CDx""##k&7&77$${'9'99
 '"- ++- 	-r)   r6   )r_   r`   ra   rb   rT   r   rd   r   r(   classmethodrc   rq   r.   r   r2   rw   r   rz   r   r4   rg   r   r9   r   r   r   torchTensorr   r   r)   r'   r<   r<     sm    S 
!!6Xk2 6t 6 GK
#s(O
.3CHo.D
	
 
  5S5[5 59U9}9 9S5[ -H 
(;/ F6 F
 9sCx 9 9/s /) )	,+ 	,%C %c %= %] %/- /- /-r)   r<   )rb   r7   collections.abcr   r   dataclassesr   	itertoolsr   typingr   r   r   torch.distributed._pycuter	   r
   r   r   r   r   r   r   r   r   r   r   r   r<   r   r)   r'   <module>r      s|     . !  %      $n, n, n,b $D-(;' D- D-r)   