U
    Jc!*                  	   @   s"  d dl Z d dlmZmZ d dlZd dlmZ d dlm	Z	 d dl
m  m  mZ d dlmZmZ d dlmZmZ d dlmZ ddlmZ ed	d
dZejejeeee ee f dddZejejejeje	eee ee f dddZejejejeje	eee ee f dddZdS )    N)ListTuple)ProcessGroup)get_split_sizeget_chunked_dim_size)
all_to_allall_to_all_single)ShardMetadata   )Shard)returnc                 C   s2   t | D ]\}}|| kr|  S qtddS )a  
    Return the position of the current rank in the given placements.

    Args:
        placements(List[Union[_remote_device, str]]):
            Specifies the placement of each shard of the Tensor. The size of
            the list represents the number of shards to be created. This could
            be a list of
            :class:`torch.distributed._remote_device`'s. This list
            could also contain a string which represents remote
            device as accepted by
            :class:`torch.distributed._remote_device`
        current_rank (int): number of current device.

    Returns:
        A int which contains the position of current device in the placement list.
    z"current_rank not in the placement.N)	enumeraterankRuntimeError)
placementscurrent_rankidx	placement r   S/tmp/pip-unpacked-wheel-gikjz4vx/torch/distributed/_shard/sharded_tensor/reshard.pyget_idx_from_placements   s    
r   )st_sizesharding_spec
world_sizer   c                 C   s   t |j}dg| }g }dgt|  }t| | |}t|jD ]b\}}	||	  t| | ||}
t	| }|
||< t
t|||	d||	 < ||  |
7  < q>||fS )a  
    Based the given sharding spec, we calculate the offset and local shard size.
    We then build a ShardMetadata on top of the calculation result.

    Args:
        st_size (torch.Size): The size of the sharded tensor.
        sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The
            specification describing how the tensor is sharded.
        world_size (int): number of ranks.

    Returns:
        A Tuple of the followings:
            A List[`ShardMetadata`] which contains the metadata for the shard, including
                offsets, lengths and device placement.
            A List[int] which contains the ranks in the order of placement.
    Nr   )shard_offsetsshard_sizesr   )intdimlenr   r   r   appendr   r   listr	   copydeepcopy)r   r   r   Z	shard_dimshards_metadataranksoffsets
split_sizer   r   sharded_dim_sizeZlocal_tensor_sizer   r   r   build_reshard_metadata/   s"    

r(   )local_shardr   r   resharding_specpgr   c                 C   s  t |}t |}t|||\}}t|j}	t||	 |}
dg| }t|j|}|j| 	 }| 
|	||< dg| }||}t||	 |
|}|||< | d|	 } t| 
 }||d< tj|| j| jd}t|| |||d} | d|	 }t||| g}||fS )a  
    Reshuffle the local shard directly when the reshard dim is same as the original
    sharding dim. Logically we do this in two step:
    1. To collect all shards based on original sharding spec.
    2. Reshard the tensor based on the given resharding spec.

    In reality, we consolidate the two steps into one by sending the local tensor to
    the new shard directly based on the resharding spec.

    Args:
        local_tensor (Tensor): Local tensor stored in the current rank.
        st_size (torch.Size): The size of the sharded tensor.
        sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The
            specification describing how the tensor is sharded originally.
        resharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The
            specification describing how the tensor will be resharded.
        pg (ProcessGroup): The process group to aggregate on.

    Returns:
        A Tuple of the followings:
            A List[`Shard`] which contains the local tensor and its metadata.
            A List[`ShardMetadata`] which contains the metadata for the shard, including
                offsets, lengths and device placement.
    r   devicedtype)input_split_sizesoutput_split_sizesgroup)distget_rankget_world_sizer(   r   r   r   r   r   r   sizeindexr   Z	transpose
contiguousr    torchemptyr-   r.   r   r   )r)   r   r   r*   r+   r   r   r#   r$   reshard_dimr&   r/   r   Znew_rankr0   Znew_idxr'   Zgathered_input_sizeZgathered_inputlocal_tensorlocal_shardsr   r   r   reshuffle_local_shardW   s>    

  



r=   )r;   r   r   r*   r+   r   c                    s  t |}t |}t|j}t|j}t|||\}	g }
|	D ]}|
|j|  q@tfddt	t
d D }|rg }|	D ]*}|j| }|j| }|t	||| 7 }q| |tj|| jd} tdg|  t|| |}d}g }t|jD ]n\}}t|| ||}t|}|||< |
| ||< tj|| j| jd | < ||  || krd}qtj| |
|d}d	d
 |D }t ||d |r fdd
|D  tj |d} t| |	| g}||	fS )a  
    Reshard a sharded tensor given the ``resharding_spec``. When the reshard dim is
    different from the original sharding dim, we need to do two steps logically:
    1. To collect all shards based on original sharding spec.
    2. Reshard the tensor based on the given resharding spec.

    In reality, we consolidate the two steps into one by sending each rank the new
    shard based on the resharding spec.

    Args:
        local_tensor (Tensor): Local tensor stored in the current rank.
        st_size (torch.Size): The size of the sharded tensor.
        sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The
            specification describing how the tensor is sharded originally.
        resharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The
            specification describing how the tensor will be resharded.
        pg (ProcessGroup): The process group to aggregate on.

    Returns:
        A Tuple of the followings:
            A List[`Shard`] which contains the local tensor and its metadata.
            A List[`ShardMetadata`] which contains the metadata for the shard, including
                offsets, lengths and device placement.
    c                 3   s"   | ]} |  |d   kV  qdS )r
   Nr   ).0i)r$   r   r   	<genexpr>   s     z&reshard_local_shard.<locals>.<genexpr>r
   )r-   Fr,   T)r   c                 S   s   g | ]}|  qS r   )r7   )r>   tensorr   r   r   
<listcomp>   s     z'reshard_local_shard.<locals>.<listcomp>)r1   c                    s   g | ]} | qS r   r   )r>   r   )output_tensor_listr   r   rB      s     )r2   r3   r4   r   r   r(   r   r   anyranger   r   Zindex_selectr8   rA   r-   r   r   r   r   r    r9   r.   r   splitr   catr   )r;   r   r   r*   r+   r   r   Zcurrent_sharding_dimr:   r#   r/   metadataZrearrange_inputindicesZoffset_start_idxr&   Zrearrange_output_listr   r   r'   Zoutput_tensor_sizeZinput_tensor_listr<   r   )rC   r$   r   reshard_local_shard   sv    



  "

     rJ   ) r!   typingr   r   r8   Ztorch.distributedZdistributedr2   Ztorch._C._distributed_c10dr   Z&torch.distributed._shard.sharding_specZ_shardr   Z
shard_specZ1torch.distributed._shard.sharding_spec._internalsr   r   Ztorch.distributed.nn.functionalr   r   Z!torch.distributed._shard.metadatar	   Zshardr   r   r   SizeZShardingSpecr(   ZTensorr=   rJ   r   r   r   r   <module>   s:   )D