U
    d3                  	   @   s<  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 d dl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!dS )    N)AnyDictListTupleOptional)distributed_c10d)ShardedTensor)ChunkShardingSpecEnumerableShardingSpecShardingSpec)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   .0Zrank)r   r   F/tmp/pip-unpacked-wheel-ua33x9lu/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	   Z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_interval<   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_sizesB   s    $z2_offsets_to_split_sizes.<locals>._offsets_to_sizesc                    sX    | \}}t  ||d }t  ||d }|||d  ||}||||d < d S r*   )bisect)Zfrom_offsetsZ
to_offsetsZsplit_sizesr/   r0   Zto_begin_rankZto_end_rankZ_split_sizes)r+   r3   r   r   _convertM   s      z)_offsets_to_split_sizes.<locals>._convertc                 S   s   g | ]}d qS r   r   r   _r   r   r   r   V   s     z+_offsets_to_split_sizes.<locals>.<listcomp>c                 S   s   g | ]}d qS r   r   r6   r   r   r   r   W   s     )r   )r'   r(   r   r   r)   r5   input_split_sizesoutput_split_sizesr   )r+   r3   r)   r   r   r   _offsets_to_split_sizes/   s    	r:   )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.)dtyper=   r   )r8   r9   group)r   sizer   intr#   numelr&   r:   sumtorchemptyr?   distZall_to_all_singlelocal_shardstensor)r;   r<   r   r)   r=   r>   Z
input_specrA   r   r'   r(   r8   r9   Zoutput_sizeZlocal_shardr   r   r   _reshard_flatten_tensor^   s0    
    rJ   )sharded_tensorpgr   c           
      C   s   |d krt  }t|}|  }|d j }|  d }|   }t	
|| | | }||  }|dkrt|d|g}tj|| |jd }	tj|	||d |	dd||  S )Nr   )r?   )r@   )r   Z_get_default_grouprG   Zget_world_sizerH   rI   flattenrA   rC   r   r   FpadrE   rF   r?   ZcudaZ_all_gather_baseZnarrowZreshape)
rK   rL   r   r   Zlocal_tensorZ
dim_0_sizer   r   Znum_paddingrI   r   r   r   _all_gather_sharded_tensor   s    
rP   )
state_dictrL   r   c                 C   s:   i }|   D ](\}}t|tr,t||}|}|||< q|S )z
    Given a state_dict, this API gathers all the ShardedTensor in the state_dict
    to the output_rank, and creates a new state_dict which the values are either
    the gathered tensors (rank == output_rank) or None (rank != output_rank).
    )itemsr   r   rP   )rQ   rL   Znew_state_dictkeyrI   Zoutput_tensorr   r   r   _gather_state_dict   s    	


rT   )N)N)"r4   r!   r   typingr   r   r   r   r   rE   Ztorch.distributedZdistributedrG   Ztorch.nn.functionalnnZ
functionalrN   r   Z'torch.distributed._shard.sharded_tensorr   Z&torch.distributed._shard.sharding_specr	   r
   r   rB   r&   r:   r=   ZProcessGroupZTensorrJ   rP   strrT   r   r   r   r   <module>   sR     05   

