U
    Jc$                  	   @   sh  d dl Z d dlZd dlZd dlmZmZmZmZmZ d dl	Z	d dl
mZ d dlm  mZ d dl
mZ d dlmZmZmZmZ d dlmZmZmZmZ eeeee dddZee ee eeeeee ee f d	d
dZeeeee	jeej  e	j!dddZ"deeej  e	j!dddZ#dee$ef eej  ee$ef dddZ%e	j!eeeej edddZ&dS )    N)AnyDictListOptionalTuple)distributed_c10d)ShardShardedTensorShardedTensorMetadataTensorProperties)ChunkShardingSpecEnumerableShardingSpecShardingSpecShardMetadata)sharding_spectensor_numel
world_sizereturnc                    s   g }t | tr,| jD ]}||jd  qnt | tr| jdksDtt	|   dkrrfddt
|D }q fddt
|D }tt|}ntdt|  d|S )z
    Translates the sharding spec to a list of offsets along dim 0. If the
    sharding spec is ChunkShardingSpec, only the ``dim`` is used and the
    placement is not used.
    r      c                    s   g | ]}| k r|n qS  r   .0rank)r   r   G/tmp/pip-unpacked-wheel-gikjz4vx/torch/distributed/fsdp/_shard_utils.py
<listcomp>(   s   z-_sharding_spec_to_offsets.<locals>.<listcomp>c                    s   g | ]}|d kr nd qS r   r   r   )
chunk_sizer   r   r   -   s     z!Un-recognized sharding spec type .)
isinstancer   shardsappendZshard_offsetsr   dimAssertionErrormathceilrangelist	itertools
accumulate
ValueErrortype)r   r   r   offsetsZshardr   )r   r   r   _sharding_spec_to_offsets   s    



r,   )input_offsetsoutput_offsetsr   r   my_rankr   c                    sj   fdd dd  fdd}dd t D }d	d t D }|| || ||| | ||fS )
z
    Given the shard offsets for each rank of the input tensor and output tensor,
    this API returns the corresponding split sizes that can be passed to
    all_to_all_single().
    c                    s8    d kr$|   |  d  d fS |   d fS d S Nr   r   r+   )r/   r   r   r   r   _get_intervalB   s    z._offsets_to_split_sizes.<locals>._get_intervalc                 S   sl   g }t | D ]Z\}}|t| d k r0| |d  n|d }||| t|| d t|| d d  q|S )Nr   r   )	enumeratelenr    max)r+   beginendZsizesioffsetZnext_offsetr   r   r   _offsets_to_sizesH   s    $z2_offsets_to_split_sizes.<locals>._offsets_to_sizesc                    sX    | \}}t  ||d }t  ||d }|||d  ||}||||d < d S r0   )bisect)Zfrom_offsetsZ
to_offsetsZsplit_sizesr6   r7   Zto_begin_rankZto_end_rankZ_split_sizes)r2   r:   r   r   _convertS   s      z)_offsets_to_split_sizes.<locals>._convertc                 S   s   g | ]}d qS r   r   r   _r   r   r   r   \   s     z+_offsets_to_split_sizes.<locals>.<listcomp>c                 S   s   g | ]}d qS r   r   r=   r   r   r   r   ]   s     )r%   )r-   r.   r   r   r/   r<   input_split_sizesoutput_split_sizesr   )r2   r:   r/   r   r   r   _offsets_to_split_sizes5   s    	rA   )input_tensoroutput_specr   r/   deviceprocess_groupr   c                 C   s   |   }|  }t|tr"td| }t|||}	t|||}
t|	|
|||\}}t|}t	j
|| j|d}tj||  d j|||d |S )a  
    Resharded a sharded flatten tensor, this is used by FSDP to do sharded
    state_dict. But the functionaility is not supported by ShardedTensor.
    This API is designed to be used for FSDP; therefore this API supports only
    1-D ShardedTensor (hence the naming, reshard_flatten_tensor).

    This API uses the ChunkShardingSpec and EnumerableShardingSpec from
    torch.distributed.sharding_spec but ignores the placement field in
    ChunkShardingSpec, as the placement requires the callees understand the
    number of GPUs per node. The API simply uses the semantics of the sharding
    specs.

    Args:
        input_tensor (ShardedTensor): the original ShardedTensor. Must be 1D.
        output_spec (ShardingSpec): the sharding spect for the output tensor.
        world_size (int): total trainer count.
        my_rank (int): the rank for this trainer.

    Returns:
        The local shard for the new ShardedTensor.
    z#The input tensor has no dimensions.dtyperD   r   )r?   r@   group)r   sizer   intr)   numelr,   rA   sumtorchemptyrG   distZall_to_all_singlelocal_shardstensor)rB   rC   r   r/   rD   rE   Z
input_specrI   r   r-   r.   r?   r@   Zoutput_sizelocal_shardr   r   r   _reshard_flatten_tensord   s0    
    rS   )sharded_tensorpgr   c                 C   s(  |d krt  }t|}|  }|  d }|   }t|| | | }t	
dt	j }|r|d j }|jst	jd|d}	| }nt	jd|d}	||  }
|
dkrt|d|
g}n t	j|| j|d}t	jd|d}	t	j|| |j|d}tj|||d |dd||  }|S )Nr   cudar   )rD   rF   )rH   )r   Z_get_default_grouprO   Zget_world_sizerP   rI   rK   r#   r$   rM   rD   rV   Zcurrent_devicerQ   flattenis_cudaZoneszerosFpadrG   rN   Z_all_gather_baseZnarrowZreshape)rT   rU   r   r   Z
dim_0_sizer   r   Zcuda_deviceZlocal_tensorZmove_to_cpuZnum_paddingrQ   r   r   r   _all_gather_sharded_tensor   s>    

  r\   )
state_dictrU   r   c                 C   s\   i }|   D ]J\}}t|trNt||}| rF| d jjrF|}n| }|||< q|S )zX
    Given a state_dict, this API gathers all the ShardedTensors in the state_dict.
    r   )itemsr   r	   r\   rP   rQ   rX   cpu)r]   rU   Znew_state_dictkeyrQ   Zoutput_tensorr   r   r   _gather_state_dict   s    


ra   )rQ   r   r   num_devices_per_noderU   r   c              
      s\  | j |dd}t||krh||  }dd |  D t|  d | | d< t||g}ng }dd |D }dgtt	
dd |D dd  }	dgt|d d	  fd
d|	D }
 fddtt|D }t|t|
  krt|ksn tdd t|
||D }t||  t| j| jdtj|  dd}tj|||dS )z
    Shard a tensor to chunks along the first dimension. The local rank will gets its
    corresponding chunk as the local shard to create a ShardedTensor.
    r   )r!   c                 S   s   g | ]}d qS r   r   r=   r   r   r   r      s     z0_create_chunk_sharded_tensor.<locals>.<listcomp>c                 S   s   g | ]}t | qS r   )r&   rI   )r   chunkr   r   r   r      s     c                 S   s   g | ]}|d  qS r   r   )r   r   r   r   r   r      s     Nr   c                    s   g | ]}|g  qS r   r   )r   Zd0r1   r   r   r      s     c                    s    g | ]}d | d|   qS )zrank:z/cuda:r   )r   r)rb   r   r   r      s    c                 S   s   g | ]\}}}t |||qS r   )r   )r   r9   rI   Z	placementr   r   r   r      s   F)rG   layoutZrequires_gradZmemory_formatZ
pin_memory)Zshards_metadatarI   Ztensor_properties)sharded_tensor_metadatarE   )rc   r4   clonerI   r#   r$   r   Zfrom_tensor_and_offsetsr&   r'   r(   r%   r"   zipr
   r   rG   rf   rM   Zcontiguous_format	is_pinnedr	   Z+_init_from_local_shards_and_global_metadata)rQ   r   r   rb   rU   chunksrR   rP   Zchunk_sizesZdim0_offsetsZchunk_offsetsZ
placementsZshard_metadatarg   r   )rb   r+   r   _create_chunk_sharded_tensor   sL    

*
rl   )N)N)'r;   r'   r#   typingr   r   r   r   r   rM   Ztorch.distributedZdistributedrO   Ztorch.nn.functionalnnZ
functionalrZ   r   Z'torch.distributed._shard.sharded_tensorr   r	   r
   r   Z&torch.distributed._shard.sharding_specr   r   r   r   rJ   r,   rA   rD   ZProcessGroupZTensorrS   r\   strra   rl   r   r   r   r   <module>   s`   	  05  ( 

